type BigStruct struct { SomeData string `json:"some_data"` DynamicField DynamicType `json:"dynamic_field"` OtherData string `json:"other_data"`}type DynamicType struct { Value interface{}}func (d *DynamicType) UnmarshalJSON(data []byte) error { var typ struct { Type string `json:"type"` } if err := json.Unmarshal(data, &typ); err != nil { return err } switch typ.Type { case "A": d.Value = new(TypeA) case "B": d.Value = new(TypeB) } return json.Unmarshal(data, d.Value)}type TypeA struct { Name string `json:"name"`}type TypeB struct { Address string `json:"address"`}
https://play.golang.com/p/oKMKQTdzp7s
如果您不想或不能更改DynamicField的类型,则可以将UnmarshalJSON方法放在BigStruct上,并声明一个临时类型以避免递归。
func (b *BigStruct) UnmarshalJSON(data []byte) error { var typ struct { DF struct { Type string `json:"type"` } `json:"dynamic_field"` } if err := json.Unmarshal(data, &typ); err != nil { return err } switch typ.DF.Type { case "A": b.DynamicField = new(DynamicTypeA) case "B": b.DynamicField = new(DynamicTypeB) } type tmp BigStruct // avoids infinite recursion return json.Unmarshal(data, (*tmp)(b))}
https://play.golang.com/p/at5Okp3VU2u
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)