首页 > 解决方案 > Marshal to JSON 结构扩展了另一个具有相同字段标签的结构

问题描述

我想struct Bar用两个id字段对包装器进行 JSON 编组,但内部使用不同的 JSON 注释(例如 `json:"foo_id"`)。我找不到办法,但它看起来应该是可行的?

在这里快速浏览一下https://golang.org/pkg/encoding/json/我找不到解决方案。

有可能吗?有什么解决办法吗?我试图避免 get/set 的所有样板在结构之间复制/粘贴值,我希望这是可行的。

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

标签: jsongostructmarshalling

解决方案


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

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

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

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

死的简单。


推荐阅读