Is there an alternative for ShouldSerialize[PropertyName] in C#?

橙三吉。 提交于 2019-12-22 13:32:36

问题


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;

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.


回答1:


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;

Note that it is important to initialize the value to the default value - hence the = -1; in the property initializer.



来源:https://stackoverflow.com/questions/50795025/is-there-an-alternative-for-shouldserializepropertyname-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!