1

Consider a bool value "IsReady"

I can set this as nullable and ignore this during serialization by NullValueHandling = NullValueHandling.Ignore or I can set the DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore

The problem here is if I need to change the the property to nullable then there are hundreds of property I need to do. Given the situation I don't think I will be allowed to do this as this will also require code change in other modules too.

The problem with second approach is the in real time there are instances where IsReady will be false and I want it to be serialized.

So I am not sure what could be the best approach here.

I would like to know if there any way to avoid serializing a property if it is null or was not set explicitly in the code.

I am using json.net

Gopi
  • 5,656
  • 22
  • 80
  • 146
  • http://stackoverflow.com/questions/1387755/can-javascriptserializer-exclude-properties-with-null-default-values Did you check this question ? – mybirthname Oct 07 '16 at 05:11
  • @mybirthname I don't want to ignore default value is it is set explicitly. – Gopi Oct 07 '16 at 05:20
  • Create another class which have same properties. And set/remove `ignore` attributes for your specific scenario. – Fabio Oct 07 '16 at 05:22
  • If you only want to serialize a property if it has been set explicitly, you're going to need to track changes made to it in your code somehow, since it is a property of the *history* of your object, not the *current state* of the object. Making the underlying field be nullable is one possibility. Another is adding an `xxxSpecified` property as described [here](https://stackoverflow.com/questions/39223335/how-to-force-newtonsoft-json-to-serialize-all-properties-strange-behavior-with/39224495#39224495). – dbc Oct 07 '16 at 05:36
  • Does your class implement `INotifyPropertyChanged`? – dbc Oct 07 '16 at 06:11
  • @dbc No. Sorry, I am not aware of this interface. – Gopi Oct 07 '16 at 06:19
  • Seems very similar to this: [Inheriting DefaultContractResolver and treating referenced entities differently](http://stackoverflow.com/q/16657918/3744182). – dbc Dec 24 '16 at 00:17

0 Answers0