将JSON解组为struct-列表中列表的类型吗?

时间:2018-07-05 19:04:35

标签: 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中的列表(在sensor catalogueactuator catalogue中)中表示列表的类型?当我用值填充JSON对象时,它将看起来像这样:

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

取消编组的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

这取决于内部切片中的类型。

任意类型?使用[][]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 
    }
}

您明白了...