【发布时间】:2018-07-27 16:09:58
【问题描述】:
我正在尝试与 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,我会得到一个填充的结构(我使用的是 this 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"
},
Name: "SB I-5, PKCL To SR 512",
StartPoint: {
Description: "I-5 @ Pierce King County Line",
Direction: "S",
Latitude: 47.255624 (float64),
Longitude: -122.33113 (float64),
MilePost: 139.41 (float64),
RoadName: "I-5"
},
TimeUpdated: "/Date(1532707200000-0700)/",
TravelTimeID: 403 (int)
}
现在,我想做的是为所有响应创建一个结构,它是 TravelTime 结构的一部分,所以我这样做了:
type TravelTimesResponse struct {
TravelTime []TravelTime
}
但是,当我调用 GetTravelTimesAsJSON 端点并将其更改为:
var foo TravelTimesResponse
我得到了 180 个(结果数)这样的空集:
{
TravelTime: TravelTime {
AverageTime: 0 (int),
CurrentTime: 0 (int),
Description: "",
Distance: 0 (float64),
EndPoint: {
Description: "",
Direction: "",
Latitude: 0 (float64),
Longitude: 0 (float64),
MilePost: 0 (float64),
RoadName: ""
},
Name: "",
StartPoint: {
Description: "",
Direction: "",
Latitude: 0 (float64),
Longitude: 0 (float64),
MilePost: 0 (float64),
RoadName: ""
},
TimeUpdated: "",
TravelTimeID: 0 (int)
}
JSON 在这里:https://gist.github.com/jaxxstorm/0ab818b300f65cf3a46cc01dbc35bf60
如果我将原来的 TravelTime 结构修改为这样的切片,它会起作用:
type TravelTimes []struct {
}
但它不能作为单个响应。
我以前曾设法做到这一点,但由于某种原因,这个失败的原因是我的大脑失败了。任何帮助表示赞赏。
【问题讨论】:
-
请发布 json api 以获取来自端点的旅行时间片。
-
这是一个带有结构数组的完整输出的要点:gist.github.com/jaxxstorm/0ab818b300f65cf3a46cc01dbc35bf60
-
我试试看,谢谢!
-
附带说明,如果 StartPoint 和 EndPoint 有自己的类型而不是直接嵌套为结构,那不是更好吗。
-
是的,一旦我让它正常工作,这就是我的意图。
标签: go