我有兩個在 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"`)}
1 回答

斯蒂芬大帝
TA貢獻1827條經驗 獲得超8個贊
對于您的示例,這看起來像:
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
}
- 1 回答
- 0 關注
- 137 瀏覽
添加回答
舉報
0/150
提交
取消