从http请求解组嵌套的json对象返回nil

gianpaolo:

我在这里也经历了其他类似的问题,但是我不知道自己在做什么错。我正在调用此API:

 https://coronavirus-tracker-api.herokuapp.com/v2/locations

它返回一个像这样的JSON对象:

{
  "latest": {
     "confirmed": 272166,
     "deaths": 11299,
     "recovered": 87256
   },
   "locations": [
    {
       "id": 0,
       "country": "Thailand",
       "country_code": "TH",
      "province": "",
      "last_updated": "2020-03-21T06:59:11.315422Z",
      "coordinates": {
        "latitude": "15",
        "longitude": "101"
     },
       "latest": {
       "confirmed": 177,
        "deaths": 1,
       "recovered": 41
      }
   },
    {
      "id": 39,
     "country": "Norway",
     "country_code": "NO",
      "province": "",
      "last_updated": "2020-03-21T06:59:11.315422Z",
      "coordinates": {
        "latitude": "60.472",
        "longitude": "8.4689"
     },
      "latest": {
        "confirmed": 1463,
        "deaths": 3,
        "recovered": 1
      }
    }
  ]
}

因此,我编写了一个小程序来解析它,但是我只能解析外部对象(“最新”),而内部数组(“ locations”)始终返回nil。

代码在这里(即使TCP调用在操场上也不起作用):

 https://play.golang.org/p/ma225d07iRA

和这里:

package main

import (
   "encoding/json"
   "fmt"
   "net/http"
   "time"
)

type AutoGenerated struct {
   Latest    Latest      `json:"latest"`
   Locations []Locations `json:"locations"`
}
type Latest struct {
   Confirmed int `json:"confirmed"`
   Deaths    int `json:"deaths"`
   Recovered int `json:"recovered"`
}
type Coordinates struct {
   Latitude  string `json:"latitude"`
   Longitude string `json:"longitude"`
}
type Locations struct {
   ID          int         `json:"id"`
   Country     string      `json:"country"`
   CountryCode string      `json:"country_code"`
   Province    string      `json:"province"`
   LastUpdated time.Time   `json:"last_updated"`
   Coordinates Coordinates `json:"coordinates"`
   Latest      Latest      `json:"latest"`
}

var latestUrl = "https://coronavirus-tracker-api.herokuapp.com/v2/latest"

func getJson(url string, target interface{}) {
   req, err := http.NewRequest("GET", url, nil)
    if err != nil {
       fmt.Println(err)
   }

   req.Header.Add("content-type", "application/json")

   res, err := http.DefaultClient.Do(req)
   if err != nil {
       fmt.Println(err)
   }

   decoder := json.NewDecoder(res.Body)
   var data AutoGenerated
   err = decoder.Decode(&data)
   if err != nil {
       fmt.Println(err)
   }

   for i, loc := range data.Locations {
       fmt.Printf("%d: %s", i, loc.Country)
   }

   defer res.Body.Close()


}

func main() {
   var a AutoGenerated
   getJson(latestUrl, &a)
}
罗德里戈·卡瓦略(Rodrigo Carvalho):

问题是端点https://coronavirus-tracker-api.herokuapp.com/v2/latest不返回locations这是我通过调用得到的响应:

{
    "latest": {
        "confirmed": 304524,
        "deaths": 12973,
        "recovered": 91499
    }
}

但是,如果您调用正确的端点https://coronavirus-tracker-api.herokuapp.com/v2/locations,则可能会起作用。

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章