go - 将 JSON 解码为结构 - 列表中的列表类型?

标签 go type-conversion unmarshalling

我正在尝试将 JSON 对象解码为 Go 中的结构。这是 JSON 对象:

{"configuration": {
        "current power source": "",
        "sensor catalogue": [[], [], [], []],
        "actuator catalogue": [[], [], [], []],
        "active interface": ""
    }
}

这是 Go 中的结构:

type Data struct{
Configuration struct {
            CurrentPowerSource string `json: "current power source"`
            SensorCatalogue  //what is the type in Go for list within a list?
            ActuatorCatalogue //each list within the list has a different type
            ActiveInterface string `json: "active interface"`
        }
}

我的问题是,如何在 Go 中的列表中表示列表的类型(在传感器目录执行器目录 中)?当我用值填充我的 JSON 对象时,它看起来像这样:

{"sensor catalogue": [["temperature", "humidity"], ["dht22"], [17], ["digital"]]}

解码的正确方法是什么?

最佳答案

这取决于内部 slice 中的类型。

任意类型?使用[][]接口(interface){}

type Data struct{
    Configuration struct {
        CurrentPowerSource string 
        SensorCatalogue    [][]interface{}
        ActuatorCatalogue  [][]interface{}
        ActiveInterface    string 
    }
}

字符串类型?使用 [][]string

type Data struct{
    Configuration struct {
        CurrentPowerSource string 
        SensorCatalogue    [][]string
        ActuatorCatalogue  [][]string
        ActiveInterface    string 
    }
}

自定义类型?使用 [][]CustomType

type Data struct{
    Configuration struct {
        CurrentPowerSource string 
        SensorCatalogue    [][]CustomType
        ActuatorCatalogue  [][]CustomType
        ActiveInterface    string 
    }
}

你明白了......

关于go - 将 JSON 解码为结构 - 列表中的列表类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51198280/

相关文章:

go - 如何分析 goroutines 的数量

c# - 对 IReadOnlyCollection 的隐式/显式转换混淆

java - JAXB 如何将嵌套的 xml 元素解码到字符串中?

json.Unmarshal 嵌套对象成字符串或 []byte

google-app-engine - 如何根据条件向数据存储区查询添加过滤器

json - 我应该如何在公共(public)库中重用结构,并更改关联的 json 字段

json - gzip 压缩到 http responseWriter

c# - 如何将 nullable int 转换为 nullable short?

在 J 中列出数字的数字

json - 如何使用键值结构数组解码 JSON,其中键没有 json 标记