Newtonsoft.Json icon indicating copy to clipboard operation
Newtonsoft.Json copied to clipboard

Feature request: JsonProperty.ShouldSerializeValue

Open mrpmorris opened this issue 8 years ago • 2 comments
trafficstars

Please take a look at the solution to this StackOverflow issue, it is the one with the Optional<T> struct.

https://stackoverflow.com/questions/12522000/optionally-serialize-a-property-based-on-its-runtime-value

This solution is not ideal because it uses reflection to access values, it also seems like quite a complicated bit of code to do something quite simple.

Could you add a JsonProperty.ShouldSerializeValue that is called with the declaring object and the value of the property about to be serialized?

Or some other solution of your choosing :) I really would like to decide whether or not to serialize a value at runtime without having to write a method for every property.

mrpmorris avatar Nov 05 '17 20:11 mrpmorris

Given there's already the ability to look for ShouldSerializeXXXX where XXXX is the name for each property, a logical extension might be the ability to define just ShouldSerialize( ) for any class, and have the serialization engine look for such a method (using reflection) on each object being serialized, and call it as necessary to determine whether it should be. It does seem that currently there's no straightforward way of defining custom behaviors for all properties of a given custom class.

wizofaus avatar Nov 12 '17 05:11 wizofaus

Still demanding for this in 2022....

a2741890 avatar May 09 '22 02:05 a2741890