在 Golang 中,json 解码器返回空结构,但 ioutil.ReadAll 显示消息

Cru*_*yro 1 go

响应结构如下:

type Response struct {
    Message string `json:"message"`
}
Run Code Online (Sandbox Code Playgroud)

代码如下:

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

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

输出如下:

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

response struct: &{}
Run Code Online (Sandbox Code Playgroud)

正如我们所看到的,响应正文字符串很好并且包含 json 字符串。但是当我尝试将响应正文解码为 json 时,我得到一个空结构。

我已经在结构中导出了 Message 字段,以便 json 包可以访问它。我在这里还缺少什么?

jee*_*tkm 5

如果您resp.Body之前已阅读过 JSON Decode,那么它没有要解码的输入。

仅尝试-

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