首页 > 解决方案 > 如何解析 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"`)
}

标签: jsongo

解决方案


您需要使用自定义解组器,如本文底部的示例:

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
}

完整的可执行示例在这里:

https://play.golang.org/p/SCpsVCgnSSK


推荐阅读