我正在尝试与 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
结构修改为像这样的 slice ,它会起作用:
type TravelTimes []struct {
}
但它不能作为单一响应。
我以前曾设法做到这一点,但出于某种原因,这次失败是我的大脑失败了。任何帮助表示赞赏。
最佳答案
解码不起作用,因为它期望顶层是一个具有字段 TravelTime
的对象,而顶层实际上是对象数组。您只想直接解码为一片对象,如下所示:
var foo []TravelTime
r.ToJSON(&foo)
关于go - 与 Golang 中的结构数组混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51561765/