调用api获取的interface类型的参数无法用[]map[string]string断言

298 阅读1分钟

问题:

调用api获取到的数据Unmarshal解析成对应的结构体后,结构体里面的字段类型为interface的字段无法用对应的直接解析。即:

type RealTimeResult struct {
   DevId string `json:"devid"`
   Code  string `json:"code"` // 0 - 成功, -1 失败
   Error string `json:"error"`
   ItemCode string      `json:"itemcode"` // 一个接口一个指标
   Result   interface{} `json:"result"`
   Ctime string `json:"ctime"`
   Rtime string `json:"rtime"`
}

本结构体的Result字段实为[]map[string]string类型,却无法断言。

解决:

造成这种问题的原因尚不清楚。 可使用reflect.TypeOf()查看具体类型。 实际解决就是需要一层一层的类型断言: 先用[]interface断言,然后循环切片用map[string]inetrface断言