在C#中,ShouldSerialize [PropertyName]是否可以替代? [英] Is there an alternative for ShouldSerialize[PropertyName] in C#?
问题描述
最近我一直在编写许多代码,这些代码涉及使用Json.NET进行序列化,并且由于我序列化的数据的性质,有时并不需要序列化其所有属性,因此,我按如下进行操作...
I have been writing a lot of code lately which involves serialization using Json.NET and due to the nature of the data that I serialize, sometimes not all of their properties need to be serialized so, I do as follows...
public int Foo { get; set; }
public bool ShouldSerializeFoo() => Foo > -1;
这很好并且可以工作,但是如果您有很多属性( 我有100多个 ),则涉及很多工作.
This's good and works but involves a lot of work if you have many properties (in my case I have over 100).
所以,我想知道编写这些方法是否还有其他选择.
So, I wanted to know if there's an alternative to writing those methods.
推荐答案
另一种选择是指定[DefaultValue(...)]
并使用DefaultValueHandling.Ignore
功能:
One alternative option is to specific a [DefaultValue(...)]
and use the DefaultValueHandling.Ignore
feature:
[DefaultValue(-1), JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public int Foo { get; set; } = -1;
请注意,将值初始化为默认值非常重要-因此,属性初始化器中的= -1;
.
Note that it is important to initialize the value to the default value - hence the = -1;
in the property initializer.
这篇关于在C#中,ShouldSerialize [PropertyName]是否可以替代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!