gpt4 book ai didi

Go 中的 JSON 和结构组合

转载 作者:IT王子 更新时间:2023-10-29 02:03:22 27 4
gpt4 key购买 nike

我的层次结构类似于此 Network -> Serie -> Season -> Episodes。这是一个简化版本,我的真实层次结构有 7 层深。

我需要使用以下 JSON 解码/编码这些对象:

Network:
{
id: 1,
name: 'Fox'
}

Series:
{
id: 2,
name: 'The Simpsons',
network: {
id: 1,
name: 'Fox'
}
}

Season:
{
id: 3,
name: 'Season 3',
network: {
id: 1,
name: 'Fox'

},
series: {
id: 2,
name: 'The Simpsons'
}
}

Episode:
{
id: 4,
name: 'Pilot',
network: {
id: 1,
name: 'Fox'
},
series: {
id: 2,
name: 'The Simpsons'
},
season: {
id: 3,
name: 'Season 3'
}
}

我尝试像这样组合我的对象:

type Base struct {
ID string `json:"id"`
Name string `json:"name"`
}

type Network struct {
Base
}

type Series struct {
Network // Flatten out all Network properties (ID + Name)
Network Base `json:"network"`
}

type Season struct {
Series // Flatten out all Series properties (ID + Name + Network)
Series Base `json:"series"`
}

type Episode struct {
Season // Flatten out all Season properties (ID + Name + Network + Series)
Season Season `json:"season"`
}

当然,由于 “重复字段错误”,它无法正常工作。此外,JSON 结果将是深度嵌套的。在经典的 OOP 中,使用普通继承这很容易,在原型(prototype)语言中它也是可行的 (Object.create/Mixins)

有没有一种优雅的方法可以用 golang 做到这一点?我宁愿保持代码干燥。

最佳答案

为什么不重命名该属性?但是保留 json 标签,go 将根据该标签编码/解码

type Base struct {
ID string `json:"id"`
Name string `json:"name"`
}

type Network struct {
Base
}

type Series struct {
Network // Flatten out all Network properties (ID + Name)
NetworkBase Base `json:"network"`
}

type Season struct {
Series // Flatten out all Series properties (ID + Name + Network)
SeriesBase Base `json:"series"`
}

type Episode struct {
Season // Flatten out all Season properties (ID + Name + Network + Series)
SeasonBase Base `json:"season"`
}

关于Go 中的 JSON 和结构组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43153181/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com