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{})


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM