亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

與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 關注
  • 344 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號