如何将嵌套结构编组为JSON?我知道如何在没有任何嵌套结构的情况下编组结构.但是,当我尝试使JSON响应看起来像这样:
{"genre": {"country": "taylor swift", "rock": "aimee"}}
我遇到了问题.
我的代码看起来像这样:
走:
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)
但是,我得到了错误
Missing type in composite literal
我该如何解决这个问题?
Cer*_*món 20
这是您的类型的复合文字:
resp := Music{
    Genre: struct {
        Country string
        Rock    string
    }{ 
        Country: "Taylor Swift",
        Rock:    "Aimee",
    },
}
您需要在文字中重复匿名类型.为避免重复,我建议为类型定义一个类型.此外,使用字段标记在输出中指定小写键名称.
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",
    },
}