我想在Go中编组和解组二叉树之类的结构。每个节点对应于Node类型的结构。节点通过指针(左右子节点)相互连接,就像在链表中一样。树的叶子承载着内容,这些内容被实现为接口。一棵树的所有叶子都具有相同类型的“内容”,即“编组器”事先已知的内容。
我知道,当在一个字段(例如“Content”)中解组具有接口的结构时,我必须执行如下类型断言err = json.Unmarshal(byteSlice, &decodedStruct{Content: &MyStruct{}})
但是,由于树的大小是任意的,因此我的结构深深地嵌套了。
有没有一种直接/惯用的方式来编组/解编这样的对象,而我却不知道呢?
下面,我发布一个最小的示例,我相信它代表了两个主要特征,一个是指针序列,另一个是在“末端”的接口。
(游乐场: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
接口,将其编组为硬编码的具体类型,然后将结果分配给该接口类型。
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
接口):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
的unmarshaler实现: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/