因此,我试图弄清楚如何获取以下代码以正确解析来自https://api.coinmarketcap.com/v1/ticker/ethereum的 JSON 数据。解码来自http://echo.jsontest.com/key1/value1/key2/value2的响应中的 JSON 数据似乎没有问题,但在指向 CoinMarketCap API 时只会获得空值/零值。
package main
import(
"encoding/json"
"net/http"
"log"
)
type JsonTest struct {
Key1 string
Key2 string
}
type CoinMarketCapData struct {
Id string
Name string
Symbol string
Rank int
PriceUSD float64
PriceBTC float64
Volume24hUSD float64
MarketCapUSD float64
AvailableSupply float64
TotalSupply float64
PercentChange1h float32
PercentChange24h float32
PercentChange7d float32
}
func getJson(url string, target interface{}) error {
client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
r, err := client.Do(req)
if err != nil {
return err
}
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(target)
}
func main() {
//Test with dummy JSON
url1 := "http://echo.jsontest.com/key1/value1/key2/value2"
jsonTest := new(JsonTest)
getJson(url1, jsonTest)
log.Printf("jsonTest Key1: %s", jsonTest.Key1)
//Test with CoinMarketCap JSON
url2 := "https://api.coinmarketcap.com/v1/ticker/ethereum"
priceData := new(CoinMarketCapData)
getJson(url2, priceData)
//Should print "Ethereum Id: ethereum"
log.Printf("Ethereum Id: %s", priceData.Id)
}
我怀疑这与 CoinMarketCap 的 JSON 位于顶级 JSON 数组中的事实有关,但我尝试了各种迭代,例如:
priceData := make([]CoinMarketCapData, 1)
无济于事。非常感谢任何建议,谢谢。
30秒到达战场
哈士奇WWW
相关分类