1 回答

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
不能鍵入斷言map[string]interface{}到map[string]float64。您需要手動(dòng)創(chuàng)建新地圖。
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?請(qǐng)參閱下面的示例。如果沒有,你怎么知道你可以首先投射它?
type response struct {
Data []struct {
Type string
Content map[string]float64
}
}
var response response
err := json.Unmarshal([]byte(exampleResponseData), &response)
- 1 回答
- 0 關(guān)注
- 201 瀏覽
添加回答
舉報(bào)