将嵌套的结构体编组为JSON。

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

Marshal nested structs into JSON

问题

你好!要将嵌套的结构体编组为JSON,你可以使用指针来解决这个问题。以下是你的代码的修改版本:

Go:

type Music struct {
  Genre *struct { 
    Country string
    Rock string
  }
}

resp := Music{
  Genre: &struct { 
    Country string
    Rock string
  }{
    Country: "Taylor Swift",
    Rock: "Aimee",
  },
}

js, _ := json.Marshal(resp)
w.Write(js)

通过将Genre字段的类型更改为指向匿名结构体的指针*struct,然后在初始化resp时使用&来创建匿名结构体的指针,你就可以成功编组嵌套的结构体了。

英文:

How do I marshal a nested struct into JSON? I know how to marshal the struct without any nested structs. However when I try to make the JSON response look like this:

{"genre": {"country": "taylor swift", "rock": "aimee"}}

I run into problems.

My code looks like this:

Go:

type Music struct {
  Genre struct { 
    Country string
    Rock string
  }
}

resp := Music{
  Genre: { // error on this line.
    Country: "Taylor Swift",
    Rock: "Aimee",
  },
}

js, _ := json.Marshal(resp)
w.Write(js)

However, I get the error

Missing type in composite literal

How do I resolve this?

答案1

得分: 37

这是你的类型的复合字面量:

resp := Music{
    Genre: struct {
        Country string
        Rock    string
    }{ 
        Country: "Taylor Swift",
        Rock:    "Aimee",
    },
}

你需要在字面量中重复匿名类型。为了避免重复,我建议为Genre定义一个类型。另外,使用字段标签来指定输出中的小写键名。

type Genre struct {
    Country string `json:"country"`
    Rock    string `json:"rock"`
}

type Music struct {
    Genre Genre `json:"genre"`
}

resp := Music{
    Genre{
        Country: "Taylor Swift",
        Rock:    "Aimee",
    },
}

playground示例

英文:

Here's the composite literal for your type:

resp := Music{
	Genre: struct {
		Country string
		Rock    string
	}{ 
		Country: "Taylor Swift",
		Rock:    "Aimee",
	},
}

playground example

You need to repeat the anonymous type in the literal. To avoid the repetition, I recommend defining a type for Genre. Also, use field tags to specify lowercase key names in the output.

type Genre struct {
  Country string `json:"country"`
  Rock    string `json:"rock"`
}

type Music struct {
  Genre Genre `json:"genre"`
}

resp := Music{
	Genre{
		Country: "Taylor Swift",
		Rock:    "Aimee",
	},
}

playground example

答案2

得分: 4

使用JsonUtils。它是一个从json文件生成Go结构的程序:
https://github.com/bashtian/jsonutils

英文:

Use JsonUtils. It is a program that generates Go structures from a json file:
https://github.com/bashtian/jsonutils

答案3

得分: 1

为什么不为结构体值设置JSON参数?
https://play.golang.org/p/n6aJdQgfom

英文:

Why not set the json param for the struct values?
https://play.golang.org/p/n6aJdQgfom

huangapple
  • 本文由 发表于 2014年12月28日 21:13:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/27676707.html
匿名

发表评论

匿名网友

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

确定