我正在尝试将 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/