如何将具有嵌入结构字段的结构编组为 Go 中的平面 JSON 对象?

package main


import (

    "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,

    })

}


人到中年有点甜
浏览 150回答 1
1回答

慕村225694

使用匿名字段来展平 JSON 输出:type City struct {&nbsp; &nbsp; City string `json:"City"`&nbsp; &nbsp; Size int&nbsp; &nbsp; &nbsp; &nbsp; `json:"Size"`}type Location struct {&nbsp; &nbsp; City&nbsp; &nbsp; &nbsp;// <-- anonymous field has type, but no field name&nbsp; &nbsp; State string `json:"State"`}该MarshalJSON方法在问题中被忽略,因为代码对Location值进行编码,但该MarshalJSON方法是使用指针接收器声明的。通过编码修复*Location。js, _ := json.Marshal(&loc)&nbsp; // <-- note &
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go