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

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

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

问题

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

  1. type InnerStruct struct {
  2. C int `json:"c"`
  3. D int `json:"d"`
  4. }
  5. type OuterStruct struct {
  6. A int `json:"a"`
  7. B []InnerStruct `json:"b"`
  8. }
  9. d := []byte(`{
  10. "a": 1,
  11. "b": [
  12. {"c": 3, "d": 4},
  13. {"c": 5, "d": 6}
  14. ]
  15. }`)
  16. var result OuterStruct
  17. err := json.Unmarshal(d, &result)
  18. if err != nil {
  19. fmt.Println("Error:", err)
  20. }

在上面的示例中,我们定义了两个结构体: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.

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

答案1

得分: 3

这个解决方案非常直观:

  1. d := []byte(`{
  2. "a": 1,
  3. "b": [
  4. {"c": 3, "d": 4},
  5. {"c": 5, "d": 6}
  6. ]
  7. }`)
  8. var j struct {
  9. A uint
  10. B []struct {
  11. C uint
  12. D uint
  13. }
  14. }
  15. if err := json.Unmarshal(d, &j); err != nil {
  16. log.Fatal(err)
  17. }
  18. fmt.Printf("%+v\n", j)

结果将打印到stdout{A:1 B:[{C:3 D:4} {C:5 D:6}]}

英文:

This solution is quite intuitive:

  1. d := []byte(`{
  2. "a": 1,
  3. "b": [
  4. {"c": 3, "d": 4},
  5. {"c": 5, "d": 6}
  6. ]
  7. }`)
  8. var j struct {
  9. A uint
  10. B []struct {
  11. C uint
  12. D uint
  13. }
  14. }
  15. if err := json.Unmarshal(d, &j); err != nil {
  16. log.Fatal(err)
  17. }
  18. 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:

确定