json - 如何在 Go 中自动向 JSON 添加类型字段?

标签 json go

如何在 Go 中为每个序列化的 JSON 自动添加一个 type 字段?

例如,在这段代码中:

type Literal struct {
  Value interface{} `json:'value'`
  Raw   string      `json:'raw'`
}

type BinaryExpression struct {
  Operator string  `json:"operator"`
  Right    Literal `json:"right"`
  Left     Literal `json:"left"`
}

os.Stdout.Write(json.Marshal(&BinaryExpression{ ... }))

而不是生成类似的东西:

{
   "operator": "*",
   "left": {
      "value": 6,
      "raw": "6"
   },
   "right": {
      "value": 7,
      "raw": "7"
   }
}

我想生成这个:

{
   "type": "BinaryExpression",
   "operator": "*",
   "left": {
      "type": "Literal",
      "value": 6,
      "raw": "6"
   },
   "right": {
      "type": "Literal",
      "value": 7,
      "raw": "7"
   }
}

最佳答案

您可以为您的结构重写 MarshalJSON 函数,以将类型注入(inject)到辅助结构中,然后返回该结构。

package main

import (
    "encoding/json"
    "os"
)

type Literal struct {
    Value interface{} `json:'value'`
    Raw   string      `json:'raw'`
}

func (l *Literal) MarshalJSON() ([]byte, error) {
    type Alias Literal
    return json.Marshal(&struct {
        Type string `json:"type"`
        *Alias
    }{
        Type:  "Literal",
        Alias: (*Alias)(l),
    })
}

type BinaryExpression struct {
    Operator string  `json:"operator"`
    Right    Literal `json:"right"`
    Left     Literal `json:"left"`
}

func (b *BinaryExpression) MarshalJSON() ([]byte, error) {
    type Alias BinaryExpression
    return json.Marshal(&struct {
        Type string `json:"type"`
        *Alias
    }{
        Type:  "BinaryExpression",
        Alias: (*Alias)(b),
    })
}

func main() {
    _ = json.NewEncoder(os.Stdout).Encode(
        &BinaryExpression{
            Operator: "*",
            Right: Literal{
                Value: 6,
                Raw:   "6",
            },
            Left: Literal{
                Value: 7,
                Raw:   "7",
            },
        })
}

关于json - 如何在 Go 中自动向 JSON 添加类型字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37612334/

相关文章:

go - 如何在 proto3 中复制未知字段功能?

json - Angular:HttpClient 错误,响应为空 200/201(总是调用 JSON.parse (""))

json - 使用 Azure 发布管道在开发、阶段和生产槽上部署期间替换/更新 json 文件的值

java - 无法解析 Android 应用程序中的 json 数组

json - 从 JSON 数据解码/编码混合对象数组

go - 添加新工作表

去错误处理,什么是使事情变干的惯用方法

json - 如何遍历 json 响应

json - 解码具有未知结构的 JSON

arrays - 将值 append 到 slice 的 slice