json字符串与struct、map的相互转换是业务开发中非常常用的,需要好好总结:
json和struct的转换
package main
import (
"encoding/json"
"github.com/davecgh/go-spew/spew"
)
type User struct {
Name string
Age int
}
func main() {
user := User{
Name: "王思聪",
Age: 20,
}
inBytes,_ := json.Marshal(&user)
jsonString := string(inBytes)
spew.Dump(jsonString)
user2 := User{}
_ = json.Unmarshal([]byte(jsonString),&user2)
spew.Dump(user2)
}
## json和map的转换
package main
import (
"encoding/json"
"github.com/davecgh/go-spew/spew"
)
func main() {
params := map[string]interface{}{
"a": 123,
"b": "战三",
}
inBytes,_ := json.Marshal(params)
jsonString := string(inBytes)
spew.Dump(jsonString)
params2 := map[string]interface{}{}
_ = json.Unmarshal([]byte(jsonString),¶ms2)
spew.Dump(params2)
for _, v := range params2 {
spew.Println(v)
}
}
|