json - Marshal to JSON 结构扩展了另一个具有相同字段标签的结构
问题描述
- 我有 2 个
struct
包含具有相同标签 (id
) 和相同 JSON 注释 (`json:"id"`) 的字段。 - 一个
struct
( ) 包括来自另一个( )Bar
的字段标签及其值。struct
Foo
我想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"}
解决方案
一个结构 (Bar) 从另一个结构 (Foo) 继承。
显然不是,因为 Go 中没有继承。
如果你想让 Foo 的 ID 命名为 foo_id:
type Foo struct {
ID int `json:"foo_id"`
Stuff string `json:"stuff"`
}
死的简单。
推荐阅读
- java - 休眠错误:查询方法公共抽象 java.util.List 的验证失败
- c - C malloc 结构抛出内存冲突异常(准系统示例)
- python - 使用 Openpyxl 突出显示单元格
- c# - 当不是每个查询都适用于我的 Click 事件时
- laravel - Laravel 的 belongsTo 方法返回 null
- flask - 如何配置 .hosts 文件以便其他设备可以访问它
- reactjs - 如果我使用自定义组件而不是普通的 HTML5 输入标签,使用 react-hook-form 的 ref 会在控制台中引发错误
- c++ - 为什么用c而不是c ++编写的postgres?c 有更好的性能还是只是历史原因?
- javascript - NgClass Error Angular(不能绑定到'ngClass',因为它不是'a'的已知属性)
- javascript - 1 次调用后阻止 Javascript 函数