如何在Go中对包含在结构体列表中的结构体进行JSON解组(unmarshal)?

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

How to JSON unmarshal a struct in a list in a struct in Go?

问题

如何将这个JSON数据反序列化为一个结构体中的数组/切片中的正确结构?我想避免反序列化为map

type InnerStruct struct {
    C int `json:"c"`
    D int `json:"d"`
}

type OuterStruct struct {
    A int           `json:"a"`
    B []InnerStruct `json:"b"`
}

d := []byte(`{
    "a": 1,
    "b": [
        {"c": 3, "d": 4},
        {"c": 5, "d": 6}
    ]
}`)

var result OuterStruct
err := json.Unmarshal(d, &result)
if err != nil {
    fmt.Println("Error:", err)
}

在上面的示例中,我们定义了两个结构体:InnerStructOuterStructInnerStruct表示JSON中的每个对象,OuterStruct表示整个JSON结构。然后,我们使用json.Unmarshal函数将JSON数据反序列化为OuterStruct类型的变量result。如果反序列化过程中出现错误,我们将打印错误信息。

英文:

How can I deserialize this JSON data into a proper struct within an array/slice within a struct? I would like to avoid deserializing to a map.

d := []byte(`{
	"a": 1,
	"b": [
		{"c": 3, "d": 4},
		{"c": 5, "d": 6}
	]
	}`)

答案1

得分: 3

这个解决方案非常直观:

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)

结果将打印到stdout{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}]}

huangapple
  • 本文由 发表于 2014年9月4日 22:01:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/25667484.html
匿名

发表评论

匿名网友

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

确定