繁体   English   中英

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

[英]How do I Marshal a struct with an embdedded struct field to be a flat JSON object in Go?

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

我想要的预期 output 是:

{"City":"San Francisco","Size":8700000,"State":"California"}

我已经阅读了这篇关于自定义 JSON 编组的博客文章,但我似乎无法让它适用于具有另一个嵌入式结构的结构。

我尝试通过定义自定义MarshalJSON function 来展平结构,但我仍然得到相同的嵌套 output:

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,
    })
}

使用匿名字段来展平 JSON output:

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 &

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM