简体   繁体   中英

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. so when its decoding the json If anyone could help me, here is my code

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 .

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 :

    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). acutions won't hold the expected data if the Json failed to parse, so you should handle that possiblity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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