我有类似于这个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"`
}
当然,由于"duplicate field error"
的原因,它不能工作。此外,JSON结果将是深度嵌套的。在经典的OOP中,使用普通继承是相当容易的,在原型语言中也是可行的(Object.create/Mixins)
有没有一种优雅的方法可以用golang来做到这一点呢?我更喜欢保持代码干燥。
发布于 2017-04-01 15:23:32
为什么不重新命名礼仪呢?但是保留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"`
}
https://stackoverflow.com/questions/43153181
复制相似问题