Marshal到JSON struct扩展了另一个具有相同字段标签的结构

时间:2018-05-22 12:49:44

标签: json go struct marshalling

  • 我有2个struct包含一个具有相同标签(id)的字段和相同的JSON注释(`json:" id"`)。
  • 一个structBar)包含来自其他structFoo)的字段标签及其值。

我想JSON使用struct字段封装包装器Bar id,但是内部具有不同的JSON注释(例如`json:" foo_id& #34;`)。我找不到办法,但它看起来应该是可行的?

快速查看https://golang.org/pkg/encoding/json/我无法找到解决方案。

有可能吗?有什么工作吗? 我试图避免get / set的所有bobo板在结构体之间复制/粘贴值,我希望这是可行的。

package main

import (
    "encoding/json"
    "fmt"
)

type Foo struct {
    ID int `json:"id"`
    Stuff string `json:"stuff"`
}

type Bar struct {
    ID int `json:"id"`
    Foo
    // the following does not work, 
    // I've tried a few variations with no luck so far
    // Foo.ID int `json:"foo_id"`
    OtherStuff string `json:"other_stuff"`
}

func main() {
    foo := Foo{ID: 123, Stuff: "abc" }
    bar := Bar{ID: 456, OtherStuff: "xyz", Foo: foo }

    fooJsonStr, _ := json.Marshal(foo)
    barJsonStr, _ := json.Marshal(bar)

    fmt.Printf("Foo: %s\n", fooJsonStr)
    fmt.Printf("Bar: %s\n", barJsonStr)
}

给出这个输出:

Foo: {"id":123,"stuff":"abc"} 
Bar: {"id":456,"stuff":"abc","other_stuff":"xyz"}

1 个答案:

答案 0 :(得分:1)

  

一个结构(Bar)继承自另一个结构(Foo)。

显然不是因为Go中没有继承。

如果你想要将Foo的ID命名为foo_id:

type Foo struct {
    ID int `json:"foo_id"`
    Stuff string `json:"stuff"`
}

死了简单。

相关问题