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

3

我正在使用一个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{},但我有些迷失方向,不确定我是否走在正确的道路上。

如果有建议,请告诉我。


7
好的,我会尽力做到最好的翻译。请查看此处:https://dev59.com/oY7ea4cB1Zd3GeqPEbHo 和 http://stackoverflow.com/questions/33569210/go-json-unmarshal-options。 - JimB
再次感谢@JimB,我使用了https://dev59.com/oY7ea4cB1Zd3GeqPEbHo来解决这个问题。花了我一些时间才理解清楚,但是现在搞定了。 - Techie210
1个回答

2

你尝试过将unmarshall转换为map[string]interface{}吗?

    type Net struct{
        Comment map[string]interface{} `json:"comment"`
    }

然后 Comment["line"] 的值可能是数组或对象。


谢谢大家。Lê Ngọc Thạch,这是最简单和最优雅的解决方案。非常感谢! - Techie210
这似乎不适用于数组情况。它只能获取单个对象。如何使用此方法迭代对象数组? - Ray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接