如何动态地在 JSON 中包含/排除结构的字段?

meh*_*hdy 5 json struct go

我有一个 ??struct Base

type Base struct {
        Name string `json:"name,omitempty"`
        // ... other fields
}
Run Code Online (Sandbox Code Playgroud)

还有两个嵌入的结构Base

type First struct {
        Base
        // ... other fields
}

type Second struct {
        Base
        // ... other fields
}
Run Code Online (Sandbox Code Playgroud)

现在我想对结构进行编组FirstSecond但有一点不同。我想将该Name字段包含在其中,First但我不想将其包含在Second.

或者为了简化这个问题,我想动态地在其 JSON 中选择加入和退出结构的字段。

注意:Name总是有价值的,我不想改变它。

Joh*_*yil 5

您可以实现Marshaler类型的接口Second并创建虚拟类型SecondClone

type SecondClone Second

func (str Second) MarshalJSON() (byt []byte, err error) {

   var temp SecondClone
   temp = SecondClone(str)
   temp.Base.Name = ""
   return json.Marshal(temp)
}
Run Code Online (Sandbox Code Playgroud)

这无需对代码进行任何其他更改即可工作。

并且它不会修改中的值,Name因为它适用于不同的类型/副本。

  • 这是不可能的!`json.Marshal(str)` 会导致一遍又一遍地调用自身,从而导致 stackoverflow (3认同)