为了账号安全,请及时绑定邮箱和手机立即绑定

与Golang中的结构体数组混淆

与Golang中的结构体数组混淆

Go
慕码人8056858 2021-04-02 13:15:00
我正在尝试与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 {}但是它不能作为一个单独的响应。我以前已经做到了,但是由于某种原因,这种失败使我的大脑无法正常工作。任何帮助表示赞赏。
查看完整描述

2 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

解组不起作用是因为它期望顶层是具有field的对象TravelTime,而顶层实际上是对象数组。您只想直接解组成一片对象,就像这样:

  var foo []TravelTime
  r.ToJSON(&foo)


查看完整回答
反对 回复 2021-04-19
  • 2 回答
  • 0 关注
  • 279 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信