I'm trying to serialize an object using Newtonsoft Json.Net.
This object is an anonymous type filled with a lot of heterogenous things, mainly regular POCOs, but also some JObject
s or JArray
s.
The thing is that when adding the NullValueHandling
property to NullValueHandling.Ignore
, every null property gets ignored, but only if it's part of a "regular" .Net object. Every 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 a simple way to ignore those null values as well ? Did I miss some setting option ? Or do I have to deal with it manually ?
A
"null"
value in aJObject
is actually a non-nullJValue
withJValue.Type
equal toJTokenType.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:In the first case, the property
"z"
is present with anull
JSON value. In the second case, the property"z"
is not present. Linq-to-JSON represents the first case with a null-typeJValue
rather than havingJProperty.Value
actually be null.To prevent null tokens from creeping into your
JObject
's values, use the appropriate serializer setting when creating theJObject
from some POCO:(Note the POCO must not itself already be a
JObject
. The untyped method(s)JsonConvert.DeserializeObject(jsonString)
orJsonConvert.DeserializeObject<dynamic>(jsonString)
will by default return aJObject
when root JSON container injsonString
is a JSON object.)