我可以将嵌套的json分解为平面结构吗



在Go中,我可以将嵌套的json分解为不同的结构化结构吗?例如使嵌套变平。

{
"id":1,
"person":{
"name": "Jack"
"extra": {
"age": 21
}
}
}
type Item struct {
ID int64 `json:"id"`
Name string `json:"name"`
Age string `json:"age"`
}

您可以通过实现json.Unmarshaler接口。

func (i *Item) UnmarshalJSON(data []byte) error {
var temp struct {
ID     int64 `json:"id"`
Person struct {
Name  string `json:"name"`
Extra struct {
Age int `json:"age"`
} `json:"extra"`
} `json:"person"`
}
if err := json.Unmarshal(data, &temp); err != nil {
return err
}
i.ID = temp.ID
i.Name = temp.Person.Name
i.Age = strconv.Itoa(temp.Person.Extra.Age)
return nil
}

https://play.golang.com/p/nRGw8ovo7vr

最新更新