我使用的 API 对特定字段的响应有时是对象,有时是对象数组。
我创建了一个结构来解码 json 响应并且效果很好。但是,在 json 响应具有对象数组的情况下,显然解码失败。我该如何处理 Go 中的这种情况?
Single Response:
{
"net": {
"comment": {
"line": {
"$": "This space is statically assigned",
"@number": "0"
}
}
}
}
Array Response:
{
"net": {
"comment": {
"line": [
{
"$": "All abuse issues will only be responded to by the Abuse",
"@number": "0"
},
{
"$": "Team through the contact info found on handle ABUSE223-ARIN",
"@number": "1"
}
]
}
}
}
我想过创建 2 个版本的结构,然后以某种方式确定我返回的是哪个实例,但这感觉很浪费。我也尝试过解码到 map[string]instance{} 但我有点迷路,不确定我是否走在正确的道路上。
如有任何建议,我们将不胜感激。
最佳答案
你试过解码到 map[string]interface{} 吗?
type Net struct{
Comment map[string]interface{} `json:"comment"`
}
那么 Comment["line"] 的值可能是数组或对象。
关于JSON 有时是数组有时是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33622016/