与Golang中的结构体数组混淆

我正在尝试与JSON API进行交互。它有两个端点:


GetTravelTimeAsJSON-指定一个旅行时间ID,它返回一个旅行时间GetTravelTimesAsJSON-返回一个包含以上所有TravelTimes的数组。


所以我有一个像这样的结构:


type TravelTime struct {

  AverageTime int     `json:"AverageTime"`

  CurrentTime int     `json:"CurrentTime"`

  Description string  `json:"Description"`

  Distance    float64 `json:"Distance"`

  EndPoint    struct {

    Description string  `json:"Description"`

    Direction   string  `json:"Direction"`

    Latitude    float64 `json:"Latitude"`

    Longitude   float64 `json:"Longitude"`

    MilePost    float64 `json:"MilePost"`

    RoadName    string  `json:"RoadName"`

  } `json:"EndPoint"`

  Name       string `json:"Name"`

  StartPoint struct {

    Description string  `json:"Description"`

    Direction   string  `json:"Direction"`

    Latitude    float64 `json:"Latitude"`

    Longitude   float64 `json:"Longitude"`

    MilePost    float64 `json:"MilePost"`

    RoadName    string  `json:"RoadName"`

  } `json:"StartPoint"`

  TimeUpdated  string `json:"TimeUpdated"`

  TravelTimeID int    `json:"TravelTimeID"`

}

如果在一次旅行中这样调用API,我将得到一个填充的结构(我正在使用此req lib)


header := req.Header{

    "Accept":          "application/json",

    "Accept-Encoding": "gzip",

  }

  r, _ := req.Get("http://www.wsdot.com/Traffic/api/TravelTimes/TravelTimesREST.svc/GetTravelTimeAsJson?AccessCode=<redacted>&TravelTimeID=403", header)

  var foo TravelTime


  r.ToJSON(&foo)

  dump.Dump(foo)

如果我转储响应,它看起来像这样:


TravelTime {

  AverageTime: 14 (int),

  CurrentTime: 14 (int),

  Description: "SB I-5 Pierce King County Line To SR 512",

  Distance: 12.06 (float64),

  EndPoint:  {

    Description: "I-5 @ SR 512 in Lakewood",

    Direction: "S",

    Latitude: 47.16158351 (float64),

    Longitude: -122.481133 (float64),

    MilePost: 127.35 (float64),

    RoadName: "I-5"

  },

 

JSON在这里:https : //gist.github.com/jaxxstorm/0ab818b300f65cf3a46cc01dbc35bf60


如果我将原始TravelTime结构修改为像这样的切片,它将起作用:


type TravelTimes []struct {


}

但是它不能作为一个单独的响应。


我以前已经做到了,但是由于某种原因,这种失败使我的大脑无法正常工作。任何帮助表示赞赏。


慕码人8056858
浏览 282回答 2
2回答

互换的青春

解组不起作用是因为它期望顶层是具有field的对象TravelTime,而顶层实际上是对象数组。您只想直接解组成一片对象,就像这样:&nbsp;&nbsp;var&nbsp;foo&nbsp;[]TravelTime &nbsp;&nbsp;r.ToJSON(&foo)
打开App,查看更多内容
随时随地看视频慕课网APP