JSON 有时数组有时对象

我正在使用一个 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"

                        }

                    ]

                }

            }

}

我想过创建 struct 的 2 个版本,然后以某种方式确定我返回的实例,但这感觉很浪费。我也试过解组到 map[string]instance{} 中,但我有点迷茫,不确定我是否走上了正确的道路。


任何意见,将不胜感激。


婷婷同学_
浏览 188回答 1
1回答

慕桂英3389331

你试过解组到 map[string]interface{} 吗?    type Net struct{         Comment map[string]interface{} `json:"comment"`     }然后 Comment["line"] 值可能是数组或对象。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go