这是我第一次尝试Go,我觉得我在这里缺少一些重要的东西。尝试从Web服务解码JSON消息,但我得到的输出是:
{响应:{请求:[]}}
我真正感兴趣的是请求节点中的数据。我的for循环显然没有被调用,因为数组是空的。我觉得我的结构需要与web服务中出现的结构完全一致吗?
示例JSON:
{
"response": {
"requests": [
{
"request": {}
},
{
"request": {
"id": 589748,
"image_thumbnail": "",
"description": "Blah blah",
"status": "received",
"user": "test"
}
}
],
"count": "50",
"benchmark": 0.95516896247864,
"status": {},
"debug": {}
}
}
type Request struct {
id int `json:"id"`
description string `json:"description"`
user string `json:"user"`
}
type Requests struct {
request Request `json:"request"`
}
type Response struct {
requests []Requests `json:"requests"`
}
type RootObject struct {
response Response `json:"response"`
}
url := "<webservice>"
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var r RootObject
decoder := json.NewDecoder(resp.Body)
decoder.Decode(&r)
fmt.Printf("%+v", r)
for _, req := range r.response.requests {
fmt.Printf("%d = %s\n", req.request.id, req.request.user)
}
答案 0 :(得分:2)
字段名称需要以大写字母开头才能导出标识符。