Go

时间:2017-04-01 05:28:34

标签: json go struct marshalling encode

我有与此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有一种优雅的方式吗?我宁愿保留代码DRY。

1 个答案:

答案 0 :(得分:2)

为什么不重命名?但保留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"`
}