在 Go 中通过嵌入式 Stuct 实现 json 编组器

Joh*_*ore 5 json go

我有一个结构,我想对其进行有效的 JSON 编码:

type MyStruct struct {
    *Meta
    Contents []interface{}
}

type Meta struct {
    Id int
}
Run Code Online (Sandbox Code Playgroud)

该结构包含已知形式的元数据和未知形式的内容,内容列表是在运行时填充的,因此我实际上无法控制它们。为了提高 Go 的编组速度,我想在 Meta 结构上实现 Marshaller 接口。Marshaller 界面如下所示:

type Marshaler interface {
        MarshalJSON() ([]byte, error)
}
Run Code Online (Sandbox Code Playgroud)

请记住,元结构并不像此处所示的那么简单。我尝试通过 Meta 结构实现 Marshaler 接口,但似乎当我随后 JSON 编组 MyStruct 时,结果只是 Meta 编组接口返回的结果。

所以我的问题是:如何 JSON 编组一个结构,该结构包含带有自己的 JSON 编组器的嵌入式结构和另一个没有 JSON 编组器的结构?

ANi*_*sus 4

由于MarshalJSON匿名字段的方法*Meta将提升为MyStructencoding/json因此在编组 MyStruct 时包将使用该方法。

您可以做的是,您可以在 MyStruct 上Meta实现Marshaller接口,如下所示:

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))
}
Run Code Online (Sandbox Code Playgroud)

{“Id”:42,“内容”:[“MyForm”,12]}

操场