json - 在 Go 中通过嵌入式结构实现 json 编码器

标签 json go

我有一个结构,我想高效地进行 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 编码器的嵌入式结构和另一个没有编码器的结构?

最佳答案

由于匿名字段*MetaMarshalJSON方法会被提升为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]}

Playground

关于json - 在 Go 中通过嵌入式结构实现 json 编码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18527887/

相关文章:

postgresql - 虫 : pq duplicate key violates unique constraint

json - 从 Ruby 中的 JSON 文件解析并从嵌套哈希中提取数字

javascript - 将 Knockout js json 转换为可观察的

c# - 在 asp.net 中将 JSON 转换为 .Net 对象时出错

go - 有没有一种方法可以在 Go 中生成类似于 Python 的 `secrets` 模块的加密强随机数?

go - 使用反射访问结构中的结构字段

python - 来自 API 请求的 JSON 打印嵌套列表

ios - 如何使用json字典,让key为空value不select?

go,for循环和break,无限循环

http - 使用查询参数执行 GET 请求