如何將嵌套結構編組為 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我該如何解決?
3 回答

元芳怎么了
TA貢獻1798條經驗 獲得超7個贊
這是您的類型的復合文字:
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",
},
}
- 3 回答
- 0 關注
- 197 瀏覽
添加回答
舉報
0/150
提交
取消