go语言的string,json和map之间的关系转化

string to json

// 转化string变成json
// 第二个参数需要是一个结构体变量
json.Unmarshal([]byte, interface{})

定义要转化成json的结构体的时候,要根据json里面会包含的内容来定义结构体,且要加tag
如:

{
  "name":      "xiaoming",
  "postion":   "China",
  "studentId": "20020200202"
}

这时候结构体就要定义为:

// 大写是为了可以被外部引用
type student struct{
  Name      string `json:"name"`
  Postions  string `json:"postion"`
  StudentId string `json:"studentId"`
}

当遇到json对象是对层嵌套时

如:

{
  "name":      "xiaoming",
  "postion":   "China",
  "studentId": "20020200202",
  "friend":{
    "name": "xiaogang",
    "postion": "China"
  }
}

可以使用:

// 大写是为了可以被外部引用
type student struct{
  Name      string                 `json:"name"`
  Postions  string                 `json:"postion"`
  StudentId string                 `json:"studentId"`
  Friend    map[string]interface{} `json:"friend"`
}

若遇到更多层嵌套可以多次使用这种方式多层解构

json to string

// 通常传入的是一个map, 会返回一个[]byte和一个error
json.Marshal(interface{})
posted @ 2020-11-14 23:02  PHSix  阅读(2333)  评论(0)    收藏  举报