首页 > 代码库 > golang Marshal和Unmarshal处理json数据

golang Marshal和Unmarshal处理json数据

{
"code": 0,
"consume": 201,
"data": {
"custom_name": "神秘梦想",  
"official_dream": [   
{
"id": "7tj0g",  
"description": "眼镜1",
"target_rmb": 60000,  
"status": 1    
},
{
"id": "84Tou",
"description": "飞机",
"target_rmb": 100000,
"status": 1
},
{
"id": "",
"description": "电视机dvd",
"target_rmb": 200000,
"status": 1
},
{
"id": "o55xl",
"description": "飞机",
"target_rmb": 100000,
"status": 1
},
{
"id": "",
"description": "耳机",
"target_rmb": 2000,
"status": 1
}
]
},
"msg": "OK",
"time": 1482394019
}

将json中的official_dream数据放入定义的数组中,

首先定义一个

type Animal struct {
Id string
Description string
TargetRmb int
Status int
}类型是根据你json的类型定义,然后var animals []Animal ;

b, err := json.Marshal(dreamlist["official_dream"]) ;

将interface转化成字节流;
val := json.Unmarshal(b, &animals);将数据映射到数组中

 

golang Marshal和Unmarshal处理json数据