亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將具有嵌入結構字段的結構編組為 Go 中的平面 JSON 對象?

如何將具有嵌入結構字段的結構編組為 Go 中的平面 JSON 對象?

Go
人到中年有點甜 2023-07-26 17:05:13
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 &


查看完整回答
反對 回復 2023-07-26
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號