2016-10-22 147 views
3

我有一个结构Base如何动态地在JSON中包含/排除结构体的字段?

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

,另外两个结构的,嵌入Base

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

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

现在我要当元帅的结构FirstSecond但有一点差别。我想在First中包含Name字段,但我不想将其包含在Second中。

或者为了简化问题,我想动态地在JSON中输入和输出struct的字段。

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

回答

-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。

+0

不,它没有工作!它仍然存在! 即使它可以工作,它似乎有点令我困惑!它可能会引起一些问题! – mehdy

2

您可以实现类型为SecondMarshaler接口,并创建一个虚拟类型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中的值,因为它在不同的类型/副本上工作。

+0

它是有道理的,但我不想改变价值!有可能只是忽略'MarshalJSON'函数中的字段? – mehdy

+1

@mehdy这是最干净的解决方案。一旦你将Name属性设置为空,json.Marshal将不会解析,并且你将无法使用解串器 – Tinwor

+0

重新获得它。也许可以在Marshal()之前保存值? 'foo:= str.Base.Name; str.Base.Name =“”;结果:= json.Marshal(str); str.Base.Name = foo;返回结果' – tobiash

相关问题