无法从HTTP响应中解析JSON

疯狂范式:

因此,我试图找出如何获取以下代码以正确解析来自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)

无济于事。任何建议都非常感谢,谢谢。

超跌:

JSON是一个数组,因此您需要将数组传递给Decode方法。还记得检查返回的错误。

package main

import(
  "encoding/json"
  "net/http"
  "log"
)

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 CoinMarketCap JSON
  url2 := "https://api.coinmarketcap.com/v1/ticker/ethereum"
  priceData := make([]CoinMarketCapData, 0)
  err := getJson(url2, &priceData)
  if err != nil {
     log.Printf("Failed to decode json: %v", err)
  } else {
    //Should print "Ethereum Id: ethereum"
    log.Printf("Ethereum Id: %v", priceData[0].Id)
  }
}

运行此打印

2016/08/21 17:15:27 Ethereum Id: ethereum

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章