gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:29:15 24 4
gpt4 key购买 nike

响应结构如下:

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

最佳答案

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

仅尝试 -

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

关于go - 在 Golang 中,json 解码器返回一个空结构,但 ioutil.ReadAll 显示消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44732508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com