Go 中的 JSON 和结构组合



我的层次结构与此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 做到这一点?我宁愿保持代码干燥。

为什么不重命名礼仪?但是保留 json 标签,然后根据该标签进行封送/取消封送

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

最新更新