在Golang中,JSON解码器返回一个空结构,但ioutil.ReadAll显示了消息。

huangapple go评论61阅读模式
英文:

In Golang, json decoder returning an empty struct but ioutil.ReadAll shows the message

问题

响应结构体如下所示:

type Response struct {
    Message string `json:"message"`
}

代码如下所示:

body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))

response := &Response{}
json.NewDecoder(resp.Body).Decode(response)
fmt.Println("response struct:", response)

输出结果如下所示:

response Body: {"Message":"success"}

response struct: &{ }

从输出结果可以看出,响应体字符串是正确的,并且包含了 JSON 字符串。但是当尝试将响应体解码为 JSON 时,得到了一个空的结构体。

根据你提供的信息,我已经将 Message 字段导出到结构体中,以便 JSON 包可以访问它。在这里,你可能还缺少了一些关键的步骤。请确保以下几点:

  1. 确保 resp.Body 是可读取的,并且在解码之前没有被其他操作消耗掉。
  2. 确保响应体的内容是有效的 JSON 格式。
  3. 确保结构体字段的标签与 JSON 字段名称匹配,以便正确解码。

如果你仍然遇到问题,请提供更多的代码和上下文信息,以便我能够更好地帮助你解决问题。

英文:

The response struct is as follows:

type Response struct {
	Message string `json:"message"`
}

The code is as follows:

body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))

response := &Response{}
json.NewDecoder(resp.Body).Decode(response)
fmt.Println("response struct:", response)

The output is as follows:

response Body: {"Message":"success"}

response struct: &{}

As we can see, the response body string is fine and contains the json strin. But when I try to decode the response body to a json, I get an empty struct.

I already have the Message field exported in the struct so that the json package has access to it. What am I still missing here ?

答案1

得分: 5

如果在JSON解码之前读取了resp.Body,那么它就没有输入可以解码。

尝试只使用以下代码:

response := &Response{}
json.NewDecoder(resp.Body).Decode(response)
fmt.Println("response struct:", response)
英文:

If you have read resp.Body before the JSON Decode then it has no input to decode.

Try only -

response := &Response{}
json.NewDecoder(resp.Body).Decode(response)
fmt.Println("response struct:", response)

huangapple
  • 本文由 发表于 2017年6月24日 11:39:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/44732508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定