我有这样的json对象:
{
"action":"GetLoad",
"resource_id":"lb-cdvyel0v",
"ret_code":0,
"meter_set":[
{
"data_set":[
{
"data":[
[
1478672400,
[
1,
0
]
],
[
1,
0
],
[
0,
0
],
[
8,
0
],
[
1,
0
]
],
"eip_id":"eip-jf79ljt7"
},
{
"data":[
[
1478693280,
[
0,
0
]
],
[
1,
0
],
[
0,
0
]
],
"eip_id":"eip-mw6n6wg0"
}
],
"meter_id":"uaffic"
}
]
}
我尝试解决这个问题:
type CommonResponse struct {
Action string `json:"action"`
JobID string `json:"job_id"`
RetCode int `json:"ret_code"`
Message string `json:"message"`
}
type GetLoadResponse struct {
MeterSet []LoadMeter `json:"meter_set"`
ResourceId string `json:"resource_id"`
CommonResponse
}
type LoadMeter struct {
MeterID string `json:"meter_id"`
DataSet LoadDataSet `json:"data_set"`
}
type LoadDataSet struct {
EipID string `json:"eip_id"`
Data []interface{} `json:"data"`
}
func Get(response interface{}) {
str := `{ "action": "GetLoad", "resource_id": "lb-cdvyel0v", "ret_code": 0, "meter_set": [ { "data_set": [ { "data": [ [ 1478672400, [ 1, 0 ] ], [ 1, 0 ], [ 0, 0 ], [ 8, 0 ], [ 1, 0 ] ], "eip_id": "eip-jf79ljt7" }, { "data": [ [ 1478693280, [ 0, 0 ] ], [ 1, 0 ], [ 0, 0 ] ], "eip_id": "eip-mw6n6wg0" } ], "meter_id": "uaffic" } ] }`
result := []byte(str)
err := json.Unmarshal(result, &response)
fmt.Println(err)
}
func main() {
var res GetLoadResponse
Get(&res)
//Get(res) // Will not be wrong, but res is null
fmt.Println(res)
}
然后,我收到了这个错误: 无法将数组解组为main.LoadDataSet类型的Go值
游乐场:https://play.golang.org/p/ywFUu2MVNR
JSON数据图片:
答案 0 :(得分:1)
data_set
元素中的meter_set
是一个LoadDataSet
数组。将您的LoadMeter
更改为:
type LoadMeter struct {
MeterID string `json:"meter_id"`
DataSet []LoadDataSet `json:"data_set"`
}