英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论