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,
}
// struct 转 json string
inBytes,_ := json.Marshal(&user)
jsonString := string(inBytes)
spew.Dump(jsonString)
// json string 转 struct
user2 := User{}
_ = json.Unmarshal([]byte(jsonString),&user2)
spew.Dump(user2)
// (string) (len=29) "{\"Name\":\"王思聪\",\"Age\":20}"
// (main.User) {
// Name: (string) (len=9) "王思聪",
// Age: (int) 20
// }
}
## json字符串和map的转换
package main
import (
"encoding/json"
"github.com/davecgh/go-spew/spew"
)
func main() {
// map[string]interface{} 转 json string
params := map[string]interface{}{
"a": 123,
"b": "战三",
}
inBytes,_ := json.Marshal(params)
jsonString := string(inBytes)
spew.Dump(jsonString)
// json string 转 map[string]interface{}
params2 := map[string]interface{}{}
_ = json.Unmarshal([]byte(jsonString),¶ms2)
spew.Dump(params2)
for _, v := range params2 {
spew.Println(v)
}
// (string) (len=22) "{\"a\":123,\"b\":\"战三\"}"
// (map[string]interface {}) (len=2) {
// (string) (len=1) "a": (float64) 123,
// (string) (len=1) "b": (string) (len=6) "战三"
// }
// 123
// 战三
}