json - 解码 JSON 响应时遇到问题

标签 json go

<分区>

这是我第一次尝试使用 Go,我觉得我在这里遗漏了一些重要的东西。尝试解码来自网络服务的 JSON 消息,但我得到的输出是:

{响应:{请求:[]}}

我真正感兴趣的是请求节点中的数据。我的 for 循环显然没有被调用,因为数组是空的。我觉得我的结构需要完全按照它们在网络服务中出现的方式声明吗?

示例 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)

}

最佳答案

字段名称需要以大写字符开头才能导出标识符。

关于json - 解码 JSON 响应时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31987018/

相关文章:

json - 在go中动态编码json键

json - 使用gulp修改json文件

python - 使用 Python 提取 JSON 文件中的嵌套项

java - Jersey/JAXB : Use same POJO for HTTP POST and GET, 但在 JSON 响应中仅返回 GET 属性的子集。

web-applications - 跨多个包的全局 session 管理的命名空间/范围问题

python - 从 Bitmex API json 转换问题读取价格图表

php - Golang中是否有相当于PHP的openssl_pkey_get_private?

unit-testing - 安装go lang后无法运行go test程序

go - 如何同时收听两个 Golang channel ?

Golfing postgres 我怎样才能从查询中返回计数