如何解析Unmarshaled结构中的引用

I have two json files that I unmarshal in Go.

The first one includes a certain type of object that is referenced by ID in the second set.

// Foo
{
  "id": 5,
  "key": "value"
}

and

// Bar
{
  "name": "bar",
  "fooReferenceId": 5
}

I want to end up with a struct like

type Bar struct {
  Name string
  Foo *Foo
}

Is there a way to achieve this directly similar to how we provide json:"..." key resolver?

Something like

type Bar struct {
  Name string `json:"name"`
  Foo  *Foo   resolveFooById(`json:"fooReferenceId"`)
}

You need to use a custom unmarshaler like the example at the bottom of this post:

http://choly.ca/post/go-json-marshalling/

For your example this would look like:

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
}

Full executable example here:

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