我有以下 JSON
[{
"id": 8,
"title": "Indonesia",
"type": "country",
"attributes": {
"regionCode": "ID",
"information": {
"title": "Welcome to Indonesia",
"content": "We only serve selected areas in Indonesia.",
"image": "indo.png"
}
},
"children": [
{
"id": 9,
"title": "Jakarta",
"type": "city",
"attributes": {
"regionCode": "ID-JKT",
"information": {
"title": "Welcome to Capital City of Indonesia",
"content": "We only serve selected areas in Jabotabek",
"image": "jakarta.png"
}
}
},
{
"id": 10,
"title": "Bali",
"type": "city",
"attributes": {
"regionCode": "ID-BAL",
"information": {
"title": "Welcome to the beach city Bali",
"content": "We only serve selected areas in Bali.",
"image": "bali.png"
}
}
}
]
}]
从技术上讲,这是一个将其自身作为子节点的嵌套结构,并且子节点也可能有子节点。但当我使用 unmarshal 来解码它时,我就是无法得到正确的结果。
工作如下我可以将属性定义为单独的结构,因此假设我有 locationAttribute 结构
type locationNode []struct {
ID string `json:"id"`
Title string `json:"title"`
Type string `json:"type"`
Attributes locationAttribute `json:"attributes"`
Children []struct {
ID string `json:"id"`
Title string `json:"title"`
Type string `json:"type"`
Attributes locationAttribute `json:"attributes"`
Children []interface{} `json:"children"`
} `json:"children"`
}
但是我希望像下面这样
type locationNode []struct {
ID string `json:"id"`
Title string `json:"title"`
Type string `json:"type"`
Attributes locationAttribute `json:"attributes"`
Children []locationNode `json:"children"`
}
任何帮助将不胜感激
最佳答案
除了在 JSON 文本中 "id"
字段是数字而不是 字符串
之外,它对我有用。
省略“属性”
以使示例更短:
type locationNode struct {
ID int `json:"id"`
Title string `json:"title"`
Type string `json:"type"`
Children []locationNode `json:"children"`
}
func main() {
ln := locationNode{}
err := json.Unmarshal([]byte(src), &ln)
fmt.Printf("%+v %v\n", ln, err)
}
const src = `{
"id": 8,
"title": "Indonesia",
"type": "country",
"attributes": {
"regionCode": "ID",
"information": {
"title": "Welcome to Indonesia",
"content": "We only serve selected areas in Indonesia.",
"image": "indo.png"
}
},
"children": [
{
"id": 9,
"title": "Jakarta",
"type": "city",
"attributes": {
"regionCode": "ID-JKT",
"information": {
"title": "Welcome to Capital City of Indonesia",
"content": "We only serve selected areas in Jabotabek",
"image": "jakarta.png"
}
}
},
{
"id": 10,
"title": "Bali",
"type": "city",
"attributes": {
"regionCode": "ID-BAL",
"information": {
"title": "Welcome to the beach city Bali",
"content": "We only serve selected areas in Bali.",
"image": "bali.png"
}
}
}
]
}`
输出(在 Go Playground 上尝试):
{ID:8 Title:Indonesia Type:country Children:[{ID:9 Title:Jakarta Type:city Children:[]} {ID:10 Title:Bali Type:city Children:[]}]} <nil>
关于Go 语言中 JSON 嵌套结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41502902/