简体   繁体   English

尝试解码 json 的主体时出现错误“data1.Body undefined (type []byte has no field or method Body)”

[英]error "data1.Body undefined (type []byte has no field or method Body)" when trying to decode a json's body

So again im trying to get this data but it is returning an error of所以我再次尝试获取这些数据,但它返回一个错误

data.Body undefined (type []byte has no field or method Body)

on line 16 and 23 of this code.在此代码的第 16 和 23 行。 so when its decoding the json If anyone could help me, here is my code所以当它解码 json 如果有人可以帮助我,这是我的代码

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
}
    json.NewDecoder(data.Body).Decode(&auctions)
 data.Body undefined (type []byte has no field or method Body)

data is already the body of the response . data已经是响应的主体

json.NewDecoder expects an io.Reader but since fasthttp has already read the data into []byte , it would be more appropriate to use json.Unmarshal : json.NewDecoder期望io.Reader但由于fasthttp已经将数据读入[]byte ,因此使用json.Unmarshal会更合适

    err := json.Unmarshal(data, &auctions)
    if err != nil {
         return nil, err
    }

Don't forget to handle errors from json.Unmarshal (or, from json.Decoder.Decode for taht matter).不要忘记处理来自json.Unmarshal的错误(或者,来自json.Decoder.Decode的错误)。 acutions won't hold the expected data if the Json failed to parse, so you should handle that possiblity.如果 Json 无法解析,则acutions将无法保存预期的数据,因此您应该处理这种可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM