json解析出来为nil ,对一个嵌套json操作,取里面的单独数据。
这是json数据:
```
{
"code": 0,
"data": {
"song": {
"count": 2,
"itemlist": [{
"albummid": "001ZaCQY2OxVMg",
"docid": "4960718353595419009",
"id": "108041208",
"mid": "000lH7Do3X6Aot",
"name": "雪阳",
"singer": "鹿予"
}, {
"albummid": "001ZaCQY2OxVMg",
"docid": "4277524965976373789",
"id": "107195477",
"mid": "0004snbm3ZMeFz",
"name": "雪阳花",
"singer": "林爽"
}],
"name": "单曲",
"order": 0,
"type": 1
}
},
"subcode": 0
}
```
我试过了转结构体 取出来为nil
转各种类型也试过了,也是nil
求方案,怎么取
```go
package main
import (
"encoding/json"
"fmt"
)
//定义结构体
type Animal struct {
Code int `json:"code"`
Data smmsData `json:"data"`
Subcode int `json:"subcode"`
}
type smmsData struct {
Song smmsong `json:"song"`
}
type smmsong struct {
Count int `json:"count"`
Itemlist ltemlistong `json:"itemlist"`
Name string `json:"name"`
Order int `json:"order"`
Type int `json:"type"`
}
type ltemlistong []struct {
Albummid string `json:"albummid"`
Docid string `json:"docid"`
Id string `json:"id"`
Mid string `json:"mid"`
Name string `json:"name"`
Singer string `json:"singer"`
}
func main() {
//建立json
jsonBlob := `{
"code":0,
"data":{
"song":{
"count":2,
"itemlist":[{
"albummid":"001ZaCQY2OxVMg",
"docid":"4960718353595419009",
"id":"108041208",
"mid":"000lH7Do3X6Aot",
"name":"雪阳",
"singer":"鹿予"
},{
"albummid":"001ZaCQY2OxVMg",
"docid":"4277524965976373789",
"id":"107195477",
"mid":"0004snbm3ZMeFz",
"name":"雪阳花",
"singer":"林爽"}],
"name":"单曲",
"order":0,
"type":1}},
"subcode":0
}`
var animals Animal //定义结构体
json.Unmarshal([]byte(jsonBlob), &animals) //json解析
//打印数据
fmt.Println(animals.Code)
fmt.Println(animals.Data)
fmt.Println(animals.Data.Song.Count)
//遍历itemlist里的数据
for _, k := range animals.Data.Song.Itemlist {
fmt.Println(k.Albummid)
fmt.Println(k.Docid)
fmt.Println(k.Id)
fmt.Println(k.Mid)
fmt.Println(k.Name)
fmt.Println(k.Singer)
}
//打印数据
fmt.Println(animals.Data.Song.Name)
fmt.Println(animals.Data.Song.Order)
fmt.Println(animals.Data.Song.Type)
}
```
#9
更多评论