我有一个结构,我想高效地进行 JSON 编码:
type MyStruct struct {
*Meta
Contents []interface{}
}
type Meta struct {
Id int
}
该结构包含已知形式的元数据和未知形式的内容,内容列表是在运行时填充的,因此我无法真正控制它们。为了提高 Go 的编码速度,我想在 Meta 结构上实现 Marshaller 接口(interface)。 Marshaller 界面如下所示:
type Marshaler interface {
MarshalJSON() ([]byte, error)
}
请记住元结构并不像这里显示的那么简单。我已经尝试在 Meta 结构上实现 Marshaler 接口(interface),但似乎当我然后 JSON 编码 MyStruct 时,结果只是 Meta 编码接口(interface)返回的结果。
所以我的问题是:我如何对一个结构进行 JSON 编码,该结构包含带有自己的 JSON 编码器的嵌入式结构和另一个没有编码器的结构?
最佳答案
由于匿名字段*Meta
的MarshalJSON
方法会被提升为MyStruct
,所以encoding/json
当 MyStruct 被编码时,包将使用该方法。
你可以做的是,而不是让 Meta
实现 Marshaller
接口(interface),你可以像这样在 MyStruct 上实现接口(interface):
package main
import (
"fmt"
"encoding/json"
"strconv"
)
type MyStruct struct {
*Meta
Contents []interface{}
}
type Meta struct {
Id int
}
func (m *MyStruct) MarshalJSON() ([]byte, error) {
// Here you do the marshalling of Meta
meta := `"Id":` + strconv.Itoa(m.Meta.Id)
// Manually calling Marshal for Contents
cont, err := json.Marshal(m.Contents)
if err != nil {
return nil, err
}
// Stitching it all together
return []byte(`{` + meta + `,"Contents":` + string(cont) + `}`), nil
}
func main() {
str := &MyStruct{&Meta{Id:42}, []interface{}{"MyForm", 12}}
o, err := json.Marshal(str)
if err != nil {
panic(err)
}
fmt.Println(string(o))
}
{"Id":42,"Contents":["MyForm",12]}
关于json - 在 Go 中通过嵌入式结构实现 json 编码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18527887/