【问题标题】:Parsing a JSON response using Unmarshal [duplicate]使用 Unmarshal 解析 JSON 响应 [重复]
【发布时间】:2018-01-16 08:45:48
【问题描述】:

我正在尝试使用以下代码解析 JSON 响应:

type Token struct {
    access_token string `json:access_token`
    token_type string `json:token_type`
    expires_in int `json:expires_in`
}

homeURL := "https:/blah.com/oauth2/token"

v := url.Values{}

v.Set("client_id", "xxx")
v.Set("client_secret", "xxx")
v.Set("grant_type", "xxx")

s := v.Encode()

req, err := http.NewRequest("POST", homeURL, strings.NewReader(s))

if err != nil {
    fmt.Printf("http.NewRequest() error: %v\n", err)
    return
}

req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

var client = http.Client{}

resp, err := client.Do(req)
if err != nil {
    //error
    fmt.Printf("http.Do() error: %v\n", err)
    return
}
defer resp.Body.Close()

if resp.StatusCode == 200 {
    var token Token
    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Error parsing JSON\n")
    }

    errj := json.Unmarshal(data, &token)
    if errj != nil {
        fmt.Println("JSON PARSING ERROR")
    }
    fmt.Printf("read resp.Body successfully:\n%v\n", string(data))
    fmt.Printf("Response Headers \n%v\n", resp.Header)
    fmt.Println(token.access_token)


} else {
    fmt.Println("Request failed !" , resp.StatusCode)
}

我也试过用

json.NewDecoder(resp.Body).Decode(&token)

但是我无法填充令牌结构并且没有错误。我得到的回复看起来不错

读取 resp.Body 成功:

{"access_token":"Osq","token_type":"Bearer","expires_in":"1247"} Response Headers map[Content-Length:[384] Connection:[keep-alive] Content-Language:[en-US] Date:[Tue, 08 Aug 2017 16:52:19 GMT] Gi-Coordination-Id:[auto_--YfYqIVya0KiAv_mLLET8g] Server:[Mashery Proxy] X-Powered-By:[ASP.NET ARR/3.0 ASP.NET] Content-Type:[application/json; charset=utf-8] Pragma:[no-cache] Cache-Control:[no-cache,no-cache] Expires:[-1]]

有没有人知道我在这两种方法中做错了什么?

编辑 - 解决方案:

 type Token struct {
    Access_token string `json:access_token`
    Token_type string `json:token_type`
    Expires_in int `json:expires_in`
 }

Unmarshal 需要导出的密钥,需要大写。

【问题讨论】:

  • 请编辑您的问题以包含Token 类型的定义。
  • 这里一定有很好的复制品...
  • 注意带下划线的变量名不符合golang

标签: json go structure httpresponse


【解决方案1】:

Token 中有未导出的字段(以小写字母开头的字段)。因为这些字段没有被导出,json 看不到它们,因此无法解组它们。请阅读the documentation for json.Unmarshal

为了将 JSON 解组为一个结构,Unmarshal 匹配传入的对象 Marshal 使用的键的键(结构字段名称或其 标签),更喜欢完全匹配但也接受不区分大小写 匹配。 Unmarshal 只会设置结构的导出字段。

【讨论】:

  • 这次你赢了;)
  • 将近 30 秒 ;)
  • @Adrian 你发现了......用太多语言编程。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-07-12
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 2018-09-14
  • 2013-06-26
  • 1970-01-01
相关资源
最近更新 更多