无法解码JSON响应
问题描述:
I have the following response from a graph api
{
"data": [
{
"name": "Mohamed Galib",
"id": "502008940"
},
{
"name": "Mebin Joseph",
"id": "503453614"
},
{
"name": "Rohith Raveendranath",
"id": "507482441"
}
],
"paging": {
"next": "https://some_url"
}
}
I have a struct as follows
type Item struct {
Name, Id string
}
I wanted to parse the response and get an array of Item, How do I do that?
我从图形API得到以下响应 p>
{
“数据”:[
{
“名称”:“穆罕默德·加里布”,
“ id”:“ 502008940”
},
{
“名称”:“梅宾·约瑟夫”,
“ id”:“ 503453614”
},
{
“ name”:“ Rohith Raveendranath”,
“ id”:“ 507482441”
}
],
“ paging”:{
“ next”:“ https:// some_url”
}
}
code> pre>
我有如下结构 p>
type Item struct {
名称,ID字符串
}
code> pre>
我想解析响应并获取Item数组,我该如何 这样吗? p>
div>
答
You need to update your struct like so:
type Item struct {
Name string `json:"name"`
Id string `json:"id"`
}
and add a struct to represent the wrapper:
type Data struct {
Data []Item `json:"data"`
}
You can then use json.Unmarshal
to populate a Data instance.
See the example in the docs.