json如何转为struct对象 · go学习3部曲:入门,进阶,实战 · 看云
## JSON 结构
比如,请求了手机归属地的接口,json 数据返回如下:
~~~
{
"resultcode": "200",
"reason": "Return Successd!",
"result": {
"province": "浙江",
"city": "杭州",
"areacode": "0571",
"zip": "310000",
"company": "中国移动",
"card": ""
}
}
~~~
思路是这样的:
1.先将 json 转成 struct。
2.然后`json.Unmarshal()`即可。
json 转 struct ,自己手写就太麻烦了,有很多在线的工具可以直接用,如下面这个:
[https://mholt.github.io/json-to-go/](https://mholt.github.io/json-to-go/)
在左边贴上 json 后面就生成 struct 了。
用代码实现下:
~~~
type MobileInfo struct {
Resultcode string `json:"resultcode"`
Reason string `json:"reason"`
Result struct {
Province string `json:"province"`
City string `json:"city"`
Areacode string `json:"areacode"`
Zip string `json:"zip"`
Company string `json:"company"`
Card string `json:"card"`
} `json:"result"`
}
func main() {
jsonStr := `
{
"resultcode": "200",
"reason": "Return Successd!",
"result": {
"province": "浙江",
"city": "杭州",
"areacode": "0571",
"zip": "310000",
"company": "中国移动",
"card": ""
}
}
`
var mobile MobileInfo
err := json.Unmarshal([]byte(jsonStr), &mobile)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(mobile.Resultcode)
fmt.Println(mobile.Reason)
fmt.Println(mobile.Result.City)
}
~~~
输出:
~~~
200
Return Successd!
杭州
~~~