2017-04-01 25 views
1

私はこのような階層構造を持っていますNetwork -> Serie -> Season -> Episodesです。これは私の実際の階層は7レベルの深さです単純化されたバージョンです。JSONとGoの構造体

私は、次の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を保つことを好むでしょう。

答えて

2

名前を変更するのはなぜですか?しかし*はい、それは可能ですが、あなたは、オブジェクトを構築し、参照する必要がある方法で正直に言うと、そのタグ

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

に基づいてアンマーシャリング/マーシャリングしますJSONタグを維持し、行くBaseが乱雑でいっぱいになります。 たとえば、golangのバージョン(https://play.golang.org/p/4Mwx3dxck_)とGroovyの継承のアプローチ(https://cafe-huitre.appspot.com/script/5715999101812736)を比較してください。 – pablomolnar

+0

継承をサポートし、合成と埋め込みをサポートします。 https://golang.org/doc/effective_go.html#embedding –

関連する問題