我想在 Go 中编码和解码类似二叉树的结构。每个节点对应一个 Node 类型的结构。节点通过指针(左右子节点)相互连接,就像在链表中一样。树的叶子承载着作为接口(interface)实现的内容。一棵树的所有叶子都具有相同类型的内容,这是解码器事先知道的。
我知道当在一个字段中解码具有接口(interface)的结构时(比如“内容”),我必须做一个类型断言,比如err = json.Unmarshal(byteSlice, &decodedStruct{Content: &MyStruct{}})
然而,由于树的大小是任意的,我的结构是深度嵌套的。
是否有一种直接/惯用的方式来编码/解码这样一个我不知道的对象?
下面,我发布了一个最小的示例,我认为它代表了两个关键特性,第一个是指针序列,第二个是“末端”的接口(interface)。
(游乐场:https://play.golang.org/p/t9C9Hn4ONlE)
// LinkedList is a simple linked list defined by a root node
type LinkedList struct {
Name string
Root *Node
}
// Node is a list's node with Content
type Node struct {
Child *Node
C Content
}
// Content is a dummy interface
type Content interface {
CalculateSum() int
}
// MyStruct implements Content
type MyStruct struct {
ID int
Values []int
}
// CalculateSum computes the sum of the slice in the field @Values
func (ms MyStruct) CalculateSum() (s int) {
for _, i := range ms.Values {
s += i
}
return
}
func main() {
// Make a list of three nodes with content in the leaf
ms := MyStruct{2, []int{2, 4, 7}}
leaf := Node{nil, ms}
node := Node{&leaf, nil}
rootNode := Node{&node, nil}
ll := LinkedList{"list1", &rootNode}
// Encoding linked list works fine...
llEncoded, err := json.Marshal(ll)
// ...decoding doesn't:
// error decoding: json: cannot unmarshal object into Go struct field Node.Root.Child.Child.C of type main.Content
llDecoded := LinkedList{}
err = json.Unmarshal(llEncoded, &llDecoded)
fmt.Println("error decoding: ", err)
}
最佳答案
如果您知道 Content
的具体类型,你可以实现 json.Unmarshaler
接口(interface),解码为硬编码的具体类型,然后将结果分配给接口(interface)类型。
func (n *Node) UnmarshalJSON(data []byte) error {
var node struct {
Child *Node
C *MyStruct
}
if err := json.Unmarshal(data, &node); err != nil {
return err
}
n.Child = node.Child
n.C = node.C
return nil
}
https://play.golang.org/p/QOJuiLpYrze如果您需要它更灵活,您需要以某种方式告诉
json.Unmarshaler
实现json代表的具体类型。您可以这样做的一种方法是将类型信息嵌入到内容的 json 中,例如(现在借助 json.Marshaler
接口(interface)):func (ms MyStruct) MarshalJSON() ([]byte, error) {
type _MyStruct MyStruct
var out = struct {
Type string `json:"_type"`
_MyStruct
}{
Type: "MyStruct",
_MyStruct: _MyStruct(ms),
}
return json.Marshal(out)
}
更新 Node
的解码器实现相应:func (n *Node) UnmarshalJSON(data []byte) error {
var node struct {
Child *Node
C json.RawMessage
}
if err := json.Unmarshal(data, &node); err != nil {
return err
}
n.Child = node.Child
if len(node.C) > 0 && string(node.C) != `null` {
var _type struct {
Type string `json:"_type"`
}
if err := json.Unmarshal([]byte(node.C), &_type); err != nil {
return err
}
c := newContent[_type.Type]()
if err := json.Unmarshal([]byte(node.C), c); err != nil {
return err
}
n.C = c
}
return nil
}
并定义 newContent
作为一个映射,其值是返回具体类型的新实例的函数:var newContent = map[string]func() Content{
"MyStruct": func() Content { return new(MyStruct) },
// ...
}
在操场上试一试:https://play.golang.org/p/u9L0VxEG4dT
关于pointers - 解码嵌套结构和类型断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62816564/