gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:34:43 25 4
gpt4 key购买 nike

在 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

关于json - 我可以将嵌套的 json 解码为平面结构吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com