英文:
JSON sometimes array sometimes object
问题
我正在消费一个API,该API的响应中的某个字段有时是一个对象,有时是一个对象数组。
我创建了一个结构体来解析JSON响应,它工作得很好。然而,在JSON响应中包含对象数组的情况下,解析失败。在Go语言中,我该如何处理这种情况呢?
单个响应:
{
"net": {
"comment": {
"line": {
"$": "This space is statically assigned",
"@number": "0"
}
}
}
}
数组响应:
{
"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"
}
]
}
}
}
我考虑过创建两个版本的结构体,然后在某种程度上确定我得到了哪个实例,但这感觉很浪费。我还尝试将其解析为map[string]interface{},但我有点迷失,不确定我是否走在正确的道路上。
希望能得到一些建议。
英文:
I am consuming an API who's response for a particular field is sometimes and object and sometimes and array of object.
I created a struct to unmarshall the json response and it works great. However, in the instances where the json response has an array of objects, obviously the unmarshalling fails. How can I deal with this situation in 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"
}
]
}
}
}
I thought about creating 2 versions of the struct and then somehow determining which instance I got back, but this feels quite wasteful. I have also tried unmarshalling into map[string]instance{} but I got a bit lost and wasn't sure if I was headed down the right path.
Any advice would be appreciated.
答案1
得分: 2
你尝试过将其反序列化为map[string]interface{}吗?
type Net struct{
Comment map[string]interface{} json:"comment"
}
然后Comment["line"]的值可能是数组或对象。
英文:
Have you tried unmarshall into map[string]interface{}?
type Net struct{
Comment map[string]interface{} `json:"comment"`
}
Then Comment["line"] value is possible array or object.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论