Newtonsoft Json.Net serialize JObject does not ignore zeros, even with the correct settings

I am trying to serialize an object using Newtonsoft Json.Net.

This object is an anonymous type filled with many heterogeneous things, mostly regular POCOs, but also with JObject or JArray s.

The fact is that when adding the NullValueHandling property to NullValueHandling.Ignore each null property is ignored, but only if it is part of a "regular" .Net object. Each null property inside a JObject or JArray remains.

Here's a minimal example:

 var jobj = JObject.FromObject(new Anything{ x = 1, y = "bla", z = null }); var poco = new Foo { foo1 = "bar", foo2 = null }; var serialized = JsonConvert.SerializeObject(new { source1 = poco, source2 = jobj }, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore}); 

Is there an easy way to ignore these null values? Am I missing some setting? Or do I need to deal with it manually?

+5
json c #
source share
1 answer

The value of A "null" in the JObject is actually a non-zero JValue with JValue.Type equal to JTokenType.Null . It represents a JSON null value when that value really appears in JSON. I believe that it is possible to capture the difference between the two following JSON objects:

  "source2": { "z": null } "source2": { } 

In the first case, the "z" property is present with a null JSON value. In the second case, the property "z" absent. Linq-to-JSON represents the first case with a null type of JValue , and not having JProperty.Value actually a null value.

To prevent null tokens from your JObject values, use the appropriate serializer setting when creating the JObject :

  var jobj = JObject.FromObject(new { x = 1, y = "bla", z = (int?)null }, new JsonSerializer { NullValueHandling = NullValueHandling.Ignore } ); 
+15
source share

All Articles