英文:
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",
},
}
英文:
Here's the composite literal for your type:
resp := Music{
Genre: struct {
Country string
Rock string
}{
Country: "Taylor Swift",
Rock: "Aimee",
},
}
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",
},
}
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论