1 回答
TA贡献1816条经验 获得超6个赞
不能键入断言map[string]interface{}到map[string]float64。您需要手动创建新地图。
package main
import (
"encoding/json"
"fmt"
)
var exampleResponseData = `{
"Data":[
{
"Type":"pos",
"Content":{
"x":0.5,
"y":0.3
}
},
{
"Type":"vel",
"Content":{
"vx":0.1,
"vy":-0.2
}
}
]
}`
type response struct {
Data []struct {
Type string
Content interface{}
}
}
func main() {
var response response
err := json.Unmarshal([]byte(exampleResponseData), &response)
if err != nil {
fmt.Println("Cannot process not valid json")
}
for i := 0; i < len(response.Data); i++ {
response.Data[i].Content = convertMap(response.Data[i].Content)
}
}
func convertMap(originalMap interface{}) map[string]float64 {
convertedMap := map[string]float64{}
for key, value := range originalMap.(map[string]interface{}) {
convertedMap[key] = value.(float64)
}
return convertedMap
}
你确定你不能定义Content为 map[string]float64?请参阅下面的示例。如果没有,你怎么知道你可以首先投射它?
type response struct {
Data []struct {
Type string
Content map[string]float64
}
}
var response response
err := json.Unmarshal([]byte(exampleResponseData), &response)
- 1 回答
- 0 关注
- 166 浏览
添加回答
举报