为了账号安全,请及时绑定邮箱和手机立即绑定

将 JSON 嵌套字段值解组为结构字段

将 JSON 嵌套字段值解组为结构字段

Go
月关宝盒 2021-11-22 15:14:51
// Given the following struct:type MyStruct struct {  First  string  Second string  Third  string}// I would like to unmarshal the following JSON into MyStruct such as:bytes := []byte({ { "first":  { "href":"http://some/resources/1" },                    "second": { "href":"http://http://some/resources/2" },                    "third":  { "href":"http://some/resources/3" } })var s MyStructerr := json.Unmarshal(bytes, &s)fmt.Println(s.First)   // how do I make this return "http://some/resources/1" instead of   //   "map[href:http://some resources/1]"?我正在寻找的是类似于 go 字段标记与实际 JSON 对象符号的组合,我可以MyStruct像这样声明:type MyStruct struct {  First  string   `json:"first.href"`  Second string   `json:"second.href"`  Third  string   `json:"third.href"`}有任何想法吗?
查看完整描述

1 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

json 包不支持访问嵌套字段的方法(与 encoding/xml 不同)。因此,您要么必须编写自己的 Unmarshal 函数(请参阅:go 中的 JSON 解码),要么使用访问器封装字段。


查看完整回答
反对 回复 2021-11-22
  • 1 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信