将JSON嵌套字段值解组为struct字段

时间:2015-11-09 06:51:23

标签: go

// 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]"?

我正在寻找的东西类似于go字段标记与实际JSON对象表示法的组合,我可以像这样声明MyStruct

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

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