1 回答
![?](http://img1.sycdn.imooc.com/5333a1d100010c2602000200-100-100.jpg)
TA贡献1775条经验 获得超11个赞
由于您正在使用的 API 返回的数据可以是字符串或数字(在数组属性中),因此您需要将其用作该数组的每个元素的类型,因为空接口(https://tour.golang.org/methods/14)在运行时适用于任何类型。bots[]interface{}
type response struct {
Bots [][]interface{} `json:"bots"`
Total int `json:"_total"`
}
然后,在循环访问切片中的每个项目时,可以使用反射检查其类型。
理想的做法是 API 在架构中返回数据,其中每个 JSON 数组元素都与其数组中的其他元素具有相同的 JSON 类型。这将更容易解析,特别是使用像Go这样的静态类型语言。
例如,API 可以返回如下数据:
{
"bots": [
{
"stringProp": "value1",
"numberProps": [
1,
2
]
}
],
"_total": 1
}
然后,您可以编写一个表示 API 响应的结构,而无需使用空接口:
type bot struct {
StringProp string `json:"stringProp"`
NumberProps []float64 `json:"numberProps"`
}
type response struct {
Bots []bot `json:"bots"`
Total int `json:"_total"`
}
但有时您无法控制正在使用的API,因此您需要愿意以更动态的方式解析响应中的数据。如果您确实可以控制 API,则应考虑以这种方式返回数据。
- 1 回答
- 0 关注
- 59 浏览
添加回答
举报