json - 如何解析 Unmarshaled 结构中的引用
问题描述
我有两个在 Go 中解组的 json 文件。
第一个包括由第二个集合中的 ID 引用的某种类型的对象。
// Foo
{
"id": 5,
"key": "value"
}
和
// Bar
{
"name": "bar",
"fooReferenceId": 5
}
我想得到一个struct
赞
type Bar struct {
Name string
Foo *Foo
}
有没有办法直接实现这一点,类似于我们提供json:"..."
密钥解析器的方式?
就像是
type Bar struct {
Name string `json:"name"`
Foo *Foo resolveFooById(`json:"fooReferenceId"`)
}
解决方案
您需要使用自定义解组器,如本文底部的示例:
http://choly.ca/post/go-json-marshalling/
对于您的示例,这看起来像:
func (b *Bar) UnmarshalJSON(input []byte) error {
type Alias Bar
aux := &struct {
FooReferenceID int `json:"fooReferenceId"`
*Alias
}{
Alias: (*Alias)(b),
}
if err := json.Unmarshal(input, &aux); err != nil {
return err
}
for index, foo := range foos {
if foo.ID == aux.FooReferenceID {
b.Foo = &foos[index]
break
}
}
return nil
}
完整的可执行示例在这里:
推荐阅读
- angular6 - Angular 中是否有可用的 ace.js 组件,它也可以用作 FormControl
- c++ - 如何在调用原始方法之前覆盖全局方法名称以将我的代码推送到前面
- python - Python 用条件断言
- android - 通过拖动更改项目位置后保存recyclerview
- ios - 在 mac 上的传输工具中打开时配置文件无效
- android - 为名为 Redmi K20 PRO 的特定设备安装动态功能模块时出现错误 INSUFFICIENT_STORAGE = -10
- python - Python“SyntaxError:无效语法”为什么?
- python - 如何更改列表中字典中特定键的值类型?
- c# - 在检查存在后插入时 MySQl 死锁
- typescript - TypeORM save() 对象数组忽略 @PrimaryColumn() 并创建重复项