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 关注
- 106 浏览
添加回答
举报
0/150
提交
取消