如何将JSON解组到接口数组中并使用 [英] How to unmarshal JSON in to array of interface and use

查看:105
本文介绍了如何将JSON解组到接口数组中并使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解如何正确解组一些输入到inteface类型数组中的JSON数据,然后使用它.我试图使此示例代码尽可能简单,以说明我遇到的问题.可以在操场上找到代码: https://play.golang.org/p/U85J_lBJ7Zr

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. 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

输出如下:

[map [ObjectType:chair ID:1234 Brand:Blue Inc.] map [ID:5678 位置:厨房ObjectType:表格]] {}错误{}错误

[map[ObjectType:chair ID:1234 Brand:Blue Inc.] map[ID:5678 Location:Kitchen ObjectType:table]] { } false { } false

代码

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
}

推荐答案

我不确定这是否可行,因为这是您方案的简化版本.但是,执行此操作的一种方法是将两种对象类型组合为新的对象Object,然后将它们直接解组为Object,而不是使用interface{}:

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{}:

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)

}

打印:

Blue Inc.

Blue Inc.

厨房

此处的示例: https://play.golang.org/p/91F4UrQlSjJ

这篇关于如何将JSON解组到接口数组中并使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆