首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在试图解码json的正文时出错"data1.Body un定义(类型[]字节没有字段或方法主体)“

在试图解码json的正文时出错"data1.Body un定义(类型[]字节没有字段或方法主体)“
EN

Stack Overflow用户
提问于 2021-12-03 19:04:25
回答 1查看 761关注 0票数 0

因此,我再次尝试获取该数据,但它返回的错误为

代码语言:javascript
复制
data.Body undefined (type []byte has no field or method Body)

在这段代码的第16和第23行。所以当它解码json时,如果有人能帮我的话,这是我的代码

代码语言:javascript
复制
func SkyblockActiveAuctions() (structs.SkyblockActiveAuctions, error) {
    var auctions structs.SkyblockActiveAuctions
    startTime := time.Now()
    statusCode, data, err := fasthttp.Get(nil, "https://api.hypixel.net/skyblock/auctions")
    if err != nil {
        return auctions, err
    }
    fmt.Println(statusCode)
    var totalPages = auctions.TotalAuctions
    for i := 0; i < totalPages; i++ {
        statusCode, data1, err := fasthttp.Get(nil, "https://api.hypixel.net/skyblock/auctions")
        if err != nil {
            return auctions, err
        }
        fmt.Println(statusCode)
        json.NewDecoder(data1.Body).Decode(&auctions)
        fmt.Println(auctions.LastUpdated)
    }
    endTime := time.Now()
    var timeTook = endTime.Sub(startTime).Milliseconds()
    fmt.Println(data)

    json.NewDecoder(data.Body).Decode(&auctions)

    fmt.Println(auctions.LastUpdated)
    fmt.Println(timeTook)

    return auctions, err
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-03 19:17:17

代码语言:javascript
复制
    json.NewDecoder(data.Body).Decode(&auctions)

data.Body未定义(类型[]字节没有字段或方法主体)

data is already the body of the response

json.NewDecoder expects an io.Reader,但是由于fasthttp已经将数据读入[]byte,所以使用json.Unmarshal更合适。

代码语言:javascript
复制
    err := json.Unmarshal(data, &auctions)
    if err != nil {
         return nil, err
    }

不要忘记处理来自json.Unmarshal (或者json.Decoder.Decode )的错误。如果Json不能解析,acutions将不会保存预期的数据,因此您应该处理这种可能性。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70219507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档