有时JSON有时会对象数组 [英] JSON sometimes array sometimes object

查看:204
本文介绍了有时JSON有时会对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我创建了一个结构来取消对json响应的解组,并且还有一个对象,它的效果很好。但是,在json响应包含对象数组的情况下,显然解组失败。如何在Go中处理这种情况?

 单个回应:
{
净: {
comment:{
line:{
$:这个空间是静态分配的,
@number:0





$ b数组响应:
{
净:{
评论:{
line:[
{
$:所有滥用问题只会受到滥用的回应,
@number: 0
},
{
$:通过手柄ABUSE223-ARIN上的联系信息进行团队合作,
@number:1
}
]
}
}
}

我想过创建2个版本的结构,然后以某种方式确定我返回的实例,但这种感觉很浪费。我也尝试unmarshalling到地图[字符串]实例{},但我有点失落,不知道我是否正在走向正确的道路。



任何建议感谢。

解决方案

你有没有尝试unmarshall进入map [string] interface {}?

 类型网络结构{
Comment map [string] interface {}`json:comment`
}

然后评论[行]值可能是数组或对象。


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.

解决方案

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.

这篇关于有时JSON有时会对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆