首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Go中的JSON和结构组合

Go中的JSON和结构组合
EN

Stack Overflow用户
提问于 2017-04-01 13:28:34
回答 1查看 1.7K关注 0票数 1

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

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

代码语言:javascript
运行
复制
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'
   }
}

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

代码语言:javascript
运行
复制
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来做到这一点呢?我更喜欢保持代码干燥。

EN

回答 1

Stack Overflow用户

发布于 2017-04-01 15:23:32

为什么不重新命名礼仪呢?但是保留json标记,go将基于该标记进行编组/解组。

代码语言:javascript
运行
复制
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"`
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43153181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档