1 回答

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超11個(gè)贊
由于您正在使用的 API 返回的數(shù)據(jù)可以是字符串或數(shù)字(在數(shù)組屬性中),因此您需要將其用作該數(shù)組的每個(gè)元素的類型,因?yàn)榭战涌冢╤ttps://tour.golang.org/methods/14)在運(yùn)行時(shí)適用于任何類型。bots[]interface{}
type response struct {
Bots [][]interface{} `json:"bots"`
Total int `json:"_total"`
}
然后,在循環(huán)訪問(wèn)切片中的每個(gè)項(xiàng)目時(shí),可以使用反射檢查其類型。
理想的做法是 API 在架構(gòu)中返回?cái)?shù)據(jù),其中每個(gè) JSON 數(shù)組元素都與其數(shù)組中的其他元素具有相同的 JSON 類型。這將更容易解析,特別是使用像Go這樣的靜態(tài)類型語(yǔ)言。
例如,API 可以返回如下數(shù)據(jù):
{
"bots": [
{
"stringProp": "value1",
"numberProps": [
1,
2
]
}
],
"_total": 1
}
然后,您可以編寫(xiě)一個(gè)表示 API 響應(yīng)的結(jié)構(gòu),而無(wú)需使用空接口:
type bot struct {
StringProp string `json:"stringProp"`
NumberProps []float64 `json:"numberProps"`
}
type response struct {
Bots []bot `json:"bots"`
Total int `json:"_total"`
}
但有時(shí)您無(wú)法控制正在使用的API,因此您需要愿意以更動(dòng)態(tài)的方式解析響應(yīng)中的數(shù)據(jù)。如果您確實(shí)可以控制 API,則應(yīng)考慮以這種方式返回?cái)?shù)據(jù)。
- 1 回答
- 0 關(guān)注
- 81 瀏覽
添加回答
舉報(bào)