package mainimport ( "encoding/json" "fmt")type City struct { City string `json:"City"` Size int `json:"Size"`}type Location struct { City City State string `json:"State"`}func main() { city := City{City: "San Francisco", Size: 8700000} loc := Location{} loc.State = "California" loc.City = city js, _ := json.Marshal(loc) fmt.Printf("%s", js)}輸出以下內容:{"City":{"City":"San Francisco","Size":8700000},"State":"California"}我想要的預期輸出是:{"City":"San Francisco","Size":8700000,"State":"California"}我已經閱讀了這篇關于自定義 JSON 編組的博客文章,但我似乎無法讓它適用于具有另一個嵌入結構的結構。我嘗試通過定義自定義函數來展平結構MarshalJSON,但我仍然得到相同的嵌套輸出:func (l *Location) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { City string `json:"City"` Size int `json:"Size"` State string `json:"State"` }{ City: l.City.City, Size: l.City.Size, State: l.State, })}
1 回答

慕村225694
TA貢獻1880條經驗 獲得超4個贊
使用匿名字段來展平 JSON 輸出:
type City struct {
City string `json:"City"`
Size int `json:"Size"`
}
type Location struct {
City // <-- anonymous field has type, but no field name
State string `json:"State"`
}
該MarshalJSON方法在問題中被忽略,因為代碼對Location值進行編碼,但該MarshalJSON方法是使用指針接收器聲明的。通過編碼修復*Location。
js, _ := json.Marshal(&loc) // <-- note &
- 1 回答
- 0 關注
- 126 瀏覽
添加回答
舉報
0/150
提交
取消