I wander if there is an elegant way to avoid serializing a null value property using Json.net. This link shows two ways of having conditional serialization but both of them are not what I want. The first method is close to what I want but not satisfactory. For example you should create a method for each property (ShouldSerialize + 'property-name'()). This is not an elegant solution since all methods must be public and there for visible. So if you have 20 properties that means you should have 20 methods or is there a better way? The best solution would be having one method lets say OnSerialize(object property, object value); that is called when the object's properties are about to be serialized. Please help...
Asked
Active
Viewed 803 times
1 Answers
0
Check out the example shown in Null Value Handling
This sample serializes an object to JSON with NullValueHandling set to Ignore so that properties with a default value aren't included in the JSON result.
string jsonIgnoreNullValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});

ziddarth
- 1,796
- 1
- 14
- 14
-
thank you for your response. That is good enough to handle the null value properties. The only problem I have with this implementation that it returns string instead of json object. I can get json object using JObject.Parse() method. Great help! – Arman Oct 02 '15 at 21:08