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

时间:2016-10-22 13:29:37

标签: json go struct

我有一个结构Base

type Base struct {
        Name string `json:"name,omitempty"`
        // ... other fields
}

还有两个嵌入Base的结构:

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

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

现在我想要对结构FirstSecond进行元素化,但稍有不同。我想在Name中加入First字段,但我不想将其包含在Second中。

或者为了简化问题,我想动态选择加入JSON中的结构字段。

注意: Name始终具有价值,我不想更改它。

2 个答案:

答案 0 :(得分:3)

您可以为类型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)
}

这将不会对您的代码进行任何其他更改。

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

答案 1 :(得分:-1)

尝试这样的事情:

type Base struct {
    Name string `json: "name,omitempty"`
    // ... other fields
}

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

type Second struct {
    Base
    Name string `json: "-"`
    // ... other fields
}

这意味着您不能再在代码中调用Second.Base.Name,而只能调用Second.Name。