简体   繁体   English

反序列化“ oneOf”结构的Json数组

[英]Deserializing Json array of “oneOf” structures

I have JSON documents that contain an array where each item is either a string or a map representing an object. 我有JSON文档,其中包含一个数组,其中每个项目都是字符串或表示对象的映射。

{"oneOfArray": ["str1", "str2", {"SomeStruct": "value3"}, "str4", {"SomeStruct": "value5"} ]}

How can I create Go classes that represent this kind of structure and provide deserialization via the json package? 如何创建代表这种结构的Go类并通过json包提供反序列化?

There is no generic support in Go (yet), so you cannot create an array that would represent the different types of values coming from your JSON. Go还没有通用支持(因此),因此您不能创建一个表示来自JSON的不同类型值的数组。

One way is use a slice of type []interface{} , and the encoding/json package will choose types itself to unmarshal into, which will be map[string]interface{} for JSON objects. 一种方法是使用[]interface{}类型的切片,然后encoding/json包将选择要编组的类型本身,对于JSON对象,将使用map[string]interface{}

You may model the outer object with this type: 您可以使用以下类型对外部对象建模:

type Obj struct {
    OneOfArray []interface{} `json:"oneOfArray"`
}

Example unmarshaling your input: 解组输入内容的示例:

src := `{"oneOfArray": ["str1", "str2", {"SomeStruct": "value3"}, "str4", {"SomeStruct": "value5"} ]}`

var obj Obj

if err := json.Unmarshal([]byte(src), &obj); err != nil {
    panic(err)
}
fmt.Println(obj)

Output (try it on the Go Playground ): 输出(在Go Playground上尝试):

{[str1 str2 map[SomeStruct:value3] str4 map[SomeStruct:value5]]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM