[英]How to unmarshal JSON in to array of interface and use
I am having difficulty understanding how to correctly unmarshal some JSON data that goes in to an array of type inteface and then use it. 我很难理解如何正确解组一些输入到inteface类型数组中的JSON数据,然后使用它。 I tried to make this example code as simple as possible to illustrate the problem I am having.
我试图使此示例代码尽可能简单,以说明我遇到的问题。 The code can be found in the playground here: https://play.golang.org/p/U85J_lBJ7Zr
该代码可以在操场上找到: https : //play.golang.org/p/U85J_lBJ7Zr
The output looks like: 输出如下:
[map[ObjectType:chair ID:1234 Brand:Blue Inc.] map[ID:5678 Location:Kitchen ObjectType:table]] { } false { } false
[map [ObjectType:chair ID:1234 Brand:Blue Inc.] map [ID:5678 Location:Kitchen ObjectType:table]] {} false {} false
Code 码
package main
import (
"fmt"
"encoding/json"
)
type Chair struct {
ObjectType string
ID string
Brand string
}
type Table struct {
ObjectType string
ID string
Location string
}
type House struct {
Name string
Objects []interface{}
}
func main() {
var h House
data := returnJSONBlob()
err := json.Unmarshal(data, &h)
if err != nil {
fmt.Println(err)
}
fmt.Println(h.Objects)
s1, ok := h.Objects[0].(Table)
fmt.Println(s1, ok)
s2, ok := h.Objects[0].(Chair)
fmt.Println(s2, ok)
}
func returnJSONBlob() []byte {
s := []byte(`
{
"Name": "house1",
"Objects": [
{
"ObjectType": "chair",
"ID": "1234",
"Brand": "Blue Inc."
},
{
"ObjectType": "table",
"ID": "5678",
"Location": "Kitchen"
}
]
}
`)
return s
}
I'm not sure if this is practical, since this is a simplified version of your scenario. 我不确定这是否可行,因为这是您方案的简化版本。 However, one way to do this is combine the two object types to a new one,
Object
, and then unmarshal them directly to Object
instead of using interface{}
: 但是,一种方法是将这两种对象类型组合为新的对象类型
Object
,然后将它们直接解组到Object
而不是使用interface{}
:
package main
import (
"encoding/json"
"fmt"
)
type Object struct {
ObjectType string
ID string
Brand string
Location string
}
type House struct {
Name string
Objects []Object
}
func returnJSONBlob() []byte {
s := []byte(`
{
"Name": "house1",
"Objects": [
{
"ObjectType": "chair",
"ID": "1234",
"Brand": "Blue Inc."
},
{
"ObjectType": "table",
"ID": "5678",
"Location": "Kitchen"
}
]
}
`)
return s
}
func main() {
var h House
data := returnJSONBlob()
err := json.Unmarshal(data, &h)
if err != nil {
fmt.Println(err)
}
fmt.Println(h.Objects[0].Brand)
fmt.Println(h.Objects[1].Location)
}
Prints: 打印:
Blue Inc.
蓝色公司
Kitchen
厨房
Example here: https://play.golang.org/p/91F4UrQlSjJ 此处的示例: https : //play.golang.org/p/91F4UrQlSjJ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.