[英]How to JSON unmarshal a struct in a list in a struct in Go?
How can I deserialize this JSON data into a proper struct within an array/slice within a struct? 如何将该JSON数据反序列化为结构中的数组/切片中的适当结构? I would like to avoid deserializing to a
map
. 我想避免反序列化到
map
。
d := []byte(`{
"a": 1,
"b": [
{"c": 3, "d": 4},
{"c": 5, "d": 6}
]
}`)
This solution is quite intuitive: 该解决方案非常直观:
d := []byte(`{
"a": 1,
"b": [
{"c": 3, "d": 4},
{"c": 5, "d": 6}
]
}`)
var j struct {
A uint
B []struct {
C uint
D uint
}
}
if err := json.Unmarshal(d, &j); err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", j)
The result, printed to stdout
: {A:1 B:[{C:3 D:4} {C:5 D:6}]}
结果打印到
stdout
: {A:1 B:[{C:3 D:4} {C:5 D:6}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.