簡體   English   中英

將 HTTP JSON 正文響應轉換為 Go 中的映射

[英]Convert HTTP JSON body response to map in Go

我正在嘗試將 HTTP JSON 正文響應轉換為 Go 中的map[string]interface{}

這是我寫的代碼:

func fromHTTPResponse(httpResponse *http.Response, errMsg string )(APIResponse, error){
    temp, _ := strconv.Atoi(httpResponse.Status)

    var data map[string]interface{}
    resp, errResp := json.Marshal(httpResponse.Body)
    defer httpResponse.Body.Close()
    if errResp != nil {
        return APIResponse{}, errResp
    }

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

    return APIResponse{httpResponse.Status, data, (temp == OK_RESPONE_CODE), errMsg, map[string]interface{}{} }, nil
}

我成功連接到服務器。 響應的正文包含 JSON 數據。 運行代碼后,數據指向nil ,這是為什么?

http.Response.Bodyio.ReadCloser 所以使用這個:

err := json.NewDecoder(httpResponse.Body).Decode(&data)

*http.Response.Bodyio.ReadCloser類型。 而且您沒有使用正確的方法來讀取正文數據並將其轉換為[]byte 嘗試使用這個:

resp, errResp := ioutil.ReadAll(httpResponse.Body)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM