dougengqiu8031 2015-08-13 11:32 采纳率: 100%
浏览 21
已采纳

解码JSON响应时遇到问题[重复]

This question already has an answer here:

This is my first attempt at Go and I feel I'm missing something important here. Trying to decode a JSON message from a webservice but the output I'm getting is:

{response:{requests:[]}}

All I'm really interested in is the data within the request node. My for-loop obviously isn't getting called because the array is empty. I feel like my structs need to be declared exactly as they appear in the webservice?

Sample 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
", req.request.id, req.request.user)

}
</div>
  • 写回答

1条回答 默认 最新

  • doudandui1592 2015-08-13 11:35
    关注

    Field names need to begin with upper case character to be exported identifiers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?