简体   繁体   English

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

[英]Can I unmarshal nested json into flat struct

In Go can I unmarshal nested json to a different structured struct?在 Go 中,我可以将嵌套的 json 解组为不同的结构化结构吗? eg flatten out the nesting.例如展平嵌套。

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

You can by implementing the json.Unmarshaler interface.您可以通过实现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 https://play.golang.com/p/nRGw8ovo7vr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM