我正在从JSON中读取数据结构。在此过程中进行了一些转换,最终我得到了一个
我知道底层结构实际上是
我可以做以下事情:
这段代码可以正常运行,但是我觉得它很丑陋,因为我需要重构整个映射并使用两个断言。有没有一种正确的方法来强制第一个断言放弃
在Go语言中,我使用
struct
,其中一个字段的类型是interface{}
。实际上它是一个map,因此JSON将其放在了map[string]inteface{}
中。我知道底层结构实际上是
map[string]float64
,我想要像这样使用它,所以我尝试进行断言。以下代码重现了这种行为:type T interface{}
func jsonMap() T {
result := map[string]interface{}{
"test": 1.2,
}
return T(result)
}
func main() {
res := jsonMap()
myMap := res.(map[string]float64)
fmt.Println(myMap)
}
我遇到了这个错误:
panic: interface conversion: main.T is map[string]interface {}, not map[string]float64
我可以做以下事情:
func main() {
// A first assertion
res := jsonMap().(map[string]interface{})
myMap := map[string]float64{
"test": res["test"].(float64), // A second assertion
}
fmt.Println(myMap)
}
这段代码可以正常运行,但是我觉得它很丑陋,因为我需要重构整个映射并使用两个断言。有没有一种正确的方法来强制第一个断言放弃
interface{}
并使用 float64
?换句话说,如何以正确的方式执行原始断言 .(map[string]float64)
?
编辑:
我要解析的实际数据看起来像这样:[
{"Type":"pos",
"Content":{"x":0.5 , y: 0.3}} ,
{"Type":"vel",
"Content":{"vx": 0.1, "vy": -0.2}}
]
在Go语言中,我使用
struct
和encoding/json
实现以下功能。type data struct {
Type string
Content interface{}
}
// I read the JSON from a WebSocket connection
_, event, _ := c.ws.ReadMessage()
j := make([]data,0)
json.Unmarshal(event, &j)
map[string]float64
作为字段类型,而是使用interface{}
呢? - Danilomap[string]interface{}
并创建一个带有浮点键的映射。这是因为map[string]interface{}
和map[string]float64
在内存中实际上具有不同的表示方式;它不能将一个视为另一个。 (而encoding/json
使映射interface{}
键,因为 Go 在创建map
时不知道键的类型将是什么。) - twotwotwo