使用Go中的struct获取json数据

时间:2017-12-11 20:24:59

标签: json go

我在Go面临一个相当简单的问题,因为我对它完全陌生。我想从REST api中获取和打印数据。我写的代码:

package main

import (
  _"bytes"
  "encoding/json"
  "fmt"
  "io/ioutil"
  "net/http"
)

type Headers struct {
  Headers HttpHeaders `json:"headers"`
}

type HttpHeaders struct {
  Accept string
  Accept_Encoding string `json:"Accept-Encoding"`
  Accept_Language string `json:"Accept-Language"`
  Connection string
  Cookie string
  Host string
  Referer string
  Upgrade_Insecure_Requests bool `json:"Upgrade-Insecure-Requests"`
  User_Agent string `json:"User-Agent"`
}


func main() {
  url := "http://httpbin.org/headers"
  res, err := http.Get(url)
  if err != nil {
    panic(err)
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    panic(err)
  }
  var head Headers
  err = json.Unmarshal(body, &head)
  if err != nil {
    panic(err)
  }
  fmt.Printf("%+v\n", head)


}

在我做出调整之后,响应如下:

{Headers:{Accept: Accept_Encoding:gzip Accept_Language: Connection:close Cookie: Host:httpbin.org Referer: Upgrade_Insecure_Requests:false User_Agent:}}

我还有一些没有值的字段,而且Upgrade_Insecure_requests中的值似乎与通过API返回的值不匹配。

第二次编辑: 删除了标签中的空格。现在的反应看起来仍然不好。

{Headers:{Accept: Accept_Encoding:gzip Accept_Language: Connection:close Cookie: Host:httpbin.org Referer: Upgrade_Insecure_Requests:false User_Agent:Go-http-client/1.1}}

Upgrade_insecure_Requests仍为0而不是1,其他字段仍为空白。

2 个答案:

答案 0 :(得分:0)

将您的最后一行更改为

fmt.Printf("%+v\n", head)

查看您的所有字段。正如您所看到的,所有字符串都是空的。这是因为在Headers struct headers字段中没有导出(第一个字母必须是大写字母),并且没有数据将被解组到其中。此外,某些字段名称与http://httpbin.org/headers中的数据不匹配。

例如,在结构中更改Accept_Encoding字段,如下所示:

    Accept_Encoding string `json:"Accept-Encoding"`

Accept-Encoding而不是Accept_Encoding读取。

答案 1 :(得分:0)

这里有几个问题,首先必须导出“Headers”结构的“HttpHeaders”字段,其次,如果JSON密钥不相同,则必须使用JSON名称标记字段(不区分大小写):

type Headers struct {
  // The "Headers" member must have a capital "H" so that the
  // JSON marshaler knows that it can be de/serialized.
  Headers HttpHeaders
}

type HttpHeaders {
  Accept          string
  // Since the JSON key is the same as the field name we don't need a tag.
  Accept_Encoding string `json:"Accept-Encoding"`
  // Here we need a tag since the member name cannot contain a dash.
  // ...
}

请注意,“Headers”结构的“Headers”字段不需要JSON标记,因为在将JSON文档键与结构字段名称匹配时,unmarshaler会忽略大小写。也就是说,“标题”字段将由JSON键"header""Header",甚至"HEADER"填充。