【问题标题】:In Golang, json decoder returning an empty struct but ioutil.ReadAll shows the message在 Golang 中,json 解码器返回一个空结构,但 ioutil.ReadAll 显示消息
【发布时间】:2017-06-24 20:23:58
【问题描述】:

响应结构如下:

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 包可以访问它。我在这里还缺少什么?

【问题讨论】:

  • 重复但懒得查。
  • 重复的就是没有导出字段的地方。
  • 不,使用正文进行调试打印并想知道为什么再次解码它会产生空也很常见。

标签: go


【解决方案1】:

如果您在 JSON Decode 之前已阅读 resp.Body,则它没有可解码的输入。

只试一试-

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

【讨论】:

  • 是的。这确实有效,但意识到它仅在 struct Response 定义在同一个包中时才有效。如果结构的定义在不同的包中,它会给出一个空结构。此外,结构 Message 的字段已经导出(以大写字母开头)
  • 无论结构位于何处,行为都是相同的,因为您创建了一个变量并提供给解码。能否将代码添加到最后的问题中?
  • 好的。我们生成了一些简单的 json 内容,因此无法正常工作。无论如何,你的解决方案是正确的。非常感谢。
猜你喜欢
  • 2018-09-27
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 2013-10-06
相关资源
最近更新 更多