将JSON嵌套字段值解析为结构体字段

huangapple go评论76阅读模式
英文:

Unmarshal JSON nested field values into struct fields

问题

给定以下结构体:

type MyStruct struct {
  First  string
  Second string
  Third  string
}

我想将以下JSON解组成MyStruct,如下所示:

bytes := []byte(`{ "first":  { "href":"http://some/resources/1" },
                  "second": { "href":"http://http://some/resources/2" },
                  "third":  { "href":"http://some/resources/3" } }`)
var s MyStruct
err := json.Unmarshal(bytes, &s)

fmt.Println(s.First) 
  // 我该如何使其返回"http://some/resources/1"而不是"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"`
}

有什么想法吗?

英文:
// 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 MyStruct
err := 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]"?

What I'm looking for is something like a combination of go field tags with actual JSON object notation where I would be able to declare MyStruct like this:

type MyStruct struct {
  First  string   `json:"first.href"`
  Second string   `json:"second.href"`
  Third  string   `json:"third.href"`
}

Any ideas?

答案1

得分: 1

json包不支持访问嵌套字段的方法(不像encoding/xml)。因此,你要么需要编写自己的Unmarshal函数(参见:Go中的JSON解码),要么使用访问器封装字段。

英文:

The json package doesn't support a way to access nested fields (unlike encoding/xml). So you will either have to write you own Unmarshal function (see: JSON decoding in go) or encapsulate the fields with accessors.

huangapple
  • 本文由 发表于 2015年11月9日 14:51:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/33603847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定