douzachan4578 2016-08-21 23:57
浏览 64
已采纳

无法从HTTP响应中解析JSON

So, I'm trying to figure out how to get the following code to properly parse the JSON data from https://api.coinmarketcap.com/v1/ticker/ethereum. It seems to have no problem decoding the JSON data in the response from http://echo.jsontest.com/key1/value1/key2/value2, but only gets empty/zero values when pointed at the 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)
}

I suspect it's related to the fact that the JSON at CoinMarketCap is inside a top level JSON array, but I've tried various iterations of things like:

priceData := make([]CoinMarketCapData, 1)

to no avail. Any advice is much appreciated, thanks.

  • 写回答

2条回答 默认 最新

  • douyuan6490 2016-08-22 00:18
    关注

    The JSON is an array, so you need to pass an array to the Decode method. Also remember to check the returned error.

    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)
      }
    }
    

    running this prints

    2016/08/21 17:15:27 Ethereum Id: ethereum
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应