在解组JSON后尝试理解类型

  • 本文关键字:类型 JSON json go
  • 更新时间 :
  • 英文 :


我有一个映射,在那里我存储了不同的结构类型,我想检索它们,以知道我必须使用什么类型的结构来进行取消shal。当键的值直接是我需要的结构时,它就可以工作了。但如果我使用另一个结构,它就不会。

type typeStruct struct {
typeValue interface{}
}
type typeA struct {
Value string `json:"value"`
}
var types1 map[string]typeA = map[string]typeA{
"typeA": typeA{},
}
var types2 map[string]typeStruct = map[string]typeStruct{
"typeA": typeStruct{typeValue: typeA{}},
}
func main() {
jsonString := `{
"value": "value1"
}`
//this behaves as expected
resultType1 := types1["typeA"]
fmt.Println(fmt.Sprintf("type1: %T", resultType1)) //prints: type1: main.typeA
json.Unmarshal([]byte(jsonString), &resultType1)
fmt.Println(fmt.Sprintf("type1: %T", resultType1)) //prints: type1: main.typeA
fmt.Println(resultType1)                           //prints: {value1}
//Not this, the type is map[string]interface  instead of main.typeA
resultType2 := types2["typeA"].typeValue
fmt.Println(fmt.Sprintf("ntype2: %T", resultType2)) //prints: type2: main.typeA
json.Unmarshal([]byte(jsonString), &resultType2)
fmt.Println(fmt.Sprintf("type2: %T", resultType2))   //prints: type2: map[string]interface {}
fmt.Println(resultType2)                             //prints: map[value:value1]
}

Go游乐场链接

你知道发生了什么吗?我怎样才能让它正常工作?

json解组没有关于typeA的信息。它看到的是interface{}

如果您向json提供类型信息。解组后,它应该标识类型A。

resultType2 := types2["typeA"].typeValue
fmt.Println(fmt.Sprintf("ntype2: %T", resultType2)) 
ta, ok := resultType2.(typeA)
if ok {
json.Unmarshal([]byte(jsonString), &ta)
fmt.Println(fmt.Sprintf("type2: %T", ta))
fmt.Println(ta)
}

然而,在你的整个计划中,这应该如何适应仍然是一个问题。可能您需要在所有必须检查的类型上使用switch,并在Unmarshall 中使用它们

最新更新