问题
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