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

// 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"`

}

有任何想法吗?


月关宝盒
浏览 145回答 1
1回答

饮歌长啸

json 包不支持访问嵌套字段的方法(与 encoding/xml 不同)。因此,您要么必须编写自己的 Unmarshal 函数(请参阅:go 中的 JSON 解码),要么使用访问器封装字段。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go