【问题标题】:JSON sometimes array sometimes objectJSON 有时是数组 有时是对象
【发布时间】:2015-11-10 02:44:42
【问题描述】:

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

任何建议将不胜感激。

【问题讨论】:

标签: json go


【解决方案1】:

您是否尝试解组为 map[string]interface{}?

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

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

【讨论】:

  • 谢谢大家。 Lê Ngọc Thạch 这是最简单、最优雅的解决方案。非常感谢!
  • 这似乎不适用于数组情况。它只拾取单个物体。如何使用此方法遍历对象数组?
猜你喜欢
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多