2016-11-10 80 views
-1

我有JSON对象是这样的:如何使用Golang func json.Unmarshal解组这些复杂的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

游乐场:JSON数据的https://play.golang.org/p/ywFUu2MVNR

图片:

enter image description here

+0

示例JSON无效。请用正确的文字更新问题。 –

+0

你可以在play.golang.org上做到这一点,并分享链接? –

+0

我已更新ths json @Mellow Marmot – fishu

回答

1

data_setmeter_set元件是LoadDataSet阵列。将您的LoadMeter更改为:

type LoadMeter struct {                   
     MeterID string    `json:"meter_id"` 
     DataSet []LoadDataSet  `json:"data_set"` 
}