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.

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

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名