嵌入式结构的多态JSON解组 [英] Polymorphic JSON unmarshalling of embedded structs
问题描述
这里是一个示例(另请参见 https://play.golang.org/p/or7z4Xc8tN ):
Here is an example (see also 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的编组?
Is there a way to polymorphically unmarshal the field Y to either an int or a string? Or even unmarshal into A.Y at all since B.Y is defined?
我知道有些人可能建议使用诸如json.Unmarshall(data, &b.A)
之类的工具进行编组,但是我不知道我是否可以将其适合我的当前设计.
I know some might suggest unmarshalling with something like json.Unmarshall(data, &b.A)
, but I don't know if I can fit that into my current design.
推荐答案
Go唯一的多态性是接口.嵌入不提供多态性.
Go's only polymorphism is interfaces. Embedding does not offer polymorphism.
如果您试图在无法假设某个字段将是哪种类型的情况下解组JSON,则可以将interface{}
类型的字段与类型断言,fmt.Sprint
或反射类型一起使用.您应该使用哪个取决于特定的用例-一旦获得了价值,您将如何处理它?在某些时候,您必须注意它是int
还是string
,这将决定如何处理该值.
If you're trying to unmarshal JSON where you can't assume what type one of the fields is going to be, you can use a field of type interface{}
along with type assertions, fmt.Sprint
, or reflection. Which you should use depends on the particular use case - once you've got the value, what are you going to do with it? At some point you have to care if it's an int
or a string
, which will determine how you handle the value.
这篇关于嵌入式结构的多态JSON解组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!