为了账号安全,请及时绑定邮箱和手机立即绑定

如何将具有嵌入结构字段的结构编组为 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 关注
  • 66 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信