有时候JSON是数组,有时候是对象。

huangapple go评论83阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年11月10日 10:44:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/33622016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定