1 回答

TA贡献1847条经验 获得超7个赞
您必须将指向预期数据类型的指针传递给 json。昂马歇尔()。即,或 .*A*B
然而,返回并获取其地址,因此您将通过.assign_typed_data()interface{}*interface{}
更改为返回指针值 或 ,并按原样传递给,因为它已经包含指针值:assign_typed_data()*A*Bdatajson.Unmarshal()
func createValue(header string) interface{} {
switch header {
case "A":
d := new(A)
fmt.Printf("inner type is %T \n", d) // inner type is *A
return d
case "B":
d := new(B)
fmt.Printf("inner type is %T \n", d) // inner type is *B
return d
default:
return nil
}
}
测试它:
s := `{"ID":"abc","Content":[1,2,3]}`
data := createValue("A")
if err := json.Unmarshal([]byte(s), data); err != nil {
panic(err)
}
fmt.Printf("outer type is %T \n", data)
fmt.Printf("outer value is %+v \n", data)
s = `{"ID":"abc","Content":{"one":[1,2], "two":[3,4]}}`
data = createValue("B")
if err := json.Unmarshal([]byte(s), data); err != nil {
panic(err)
}
fmt.Printf("outer type is %T \n", data)
fmt.Printf("outer value is %+v \n", data)
哪些输出(在Go游乐场上尝试):
inner type is *main.A
outer type is *main.A
outer value is &{ID:abc Content:[1 2 3]}
inner type is *main.B
outer type is *main.B
outer value is &{ID:abc Content:map[one:[1 2] two:[3 4]]}
请检查相关/可能的重复项,以进一步详细说明问题:
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报