【发布时间】:2017-06-06 01:34:39
【问题描述】:
这是一个例子(另见https://play.golang.org/p/or7z4Xc8tN):
package main
import (
"encoding/json"
"fmt"
)
type A struct {
X string
Y int
}
type B struct {
A
Y string
}
func main() {
data := []byte(`{"X": "me", "Y": "hi"}`)
b := &B{}
json.Unmarshal(data, b)
fmt.Println(b)
fmt.Println(b.A)
b = &B{}
data = []byte(`{"X": "me", "Y": 123}`)
json.Unmarshal(data, b)
fmt.Println(b)
fmt.Println(b.A)
}
哪些输出:
&{{me 0} hi}
{me 0}
&{{me 0} }
{me 0}
有没有办法将字段 Y 多态地解组为 int 或字符串?或者甚至因为 B.Y 已定义而完全解组为 A.Y?
我知道有些人可能会建议使用 json.Unmarshall(data, &b.A) 之类的东西来解组,但我不知道我是否可以将它融入我当前的设计中。
【问题讨论】:
标签: json go nested polymorphism unmarshalling