dtz8044 2018-02-17 01:24
浏览 29

通过API进行解组响应

I have been working with Go and the Bitmex API.

I have the following Bitmex api endpoint:

https://www.bitmex.com/api/v1/leaderboard

This returns an array of JSON objects structured as follows.

[
  {
    "name": "string",
    "isRealName": true,
    "profit": 0
  }
]

However I get the following incorrect representation of the JSON when I marshal it.

[{0 false } {0 false } ... ]

I know my HTTP request is going through, as when I print the response.Body I get the following

[{"profit":256915996199,"isRealName":true,"name":"angelobtc"} ... ]

Here is the struct I am using to store the marshaled data.

type LeaderboardResponse struct {
    profit float64 `json:"profit"`
    isRealName bool `json:"isRealName"`
    name string `json:"name"`
}

And my main method

func main() {
    response, errorResponse := http.Get("https://www.bitmex.com/api/v1/leaderboard")
    if response.Status == "200 OK"{
        if errorResponse != nil {
        fmt.Printf("The HTTP request failed with error %s
",errorResponse)
        } else {
            body, errorBody := ioutil.ReadAll(response.Body)
            if errorBody != nil {
                fmt.Println("There was an error retrieving the body", errorBody)
            } else {
                leaderboard := []LeaderboardResponse{}
                json.Unmarshal([]byte(body),&leaderboard)
                if leaderboard != nil {
                    fmt.Println(leaderboard);
                    //The result of the statement above and the one below are different 
                    fmt.Println(string(body))
                } else {
                    fmt.Println("leaderboard array is undefined")
                }
                defer response.Body.Close()
            }
        }
    } else {
        fmt.Println("Response received with status ", string(response.Status))
    }
}

It appears that the values of struct have not been modifies despite it being assigned the marshaled JSON body

How do I fix this issue?

Furthermore,

  • How do I add my API credentials to the HTTP request?
  • How do I access the response header and marshal it?
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 制裁名单20240508芯片厂商
    • ¥20 易康econgnition精度验证
    • ¥15 线程问题判断多次进入
    • ¥15 msix packaging tool打包问题
    • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接