Newtonsoft Json.Net serialize JObject doesn’t ignore nulls, even with the right settings

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

  "source2": {
    "z": null
  }

  "source2": {
  }

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

To prevent null tokens from creeping into your JObject‘s values, use the appropriate serializer setting when creating the JObject from some POCO:

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

(Note the POCO must not itself already be a JObject. The untyped method(s) JsonConvert.DeserializeObject(jsonString) or JsonConvert.DeserializeObject<dynamic>(jsonString) will by default return a JObject when root JSON container in jsonString is a JSON object.)

Leave a Comment