I'm not finding a good reference table explaining the exact serializing and deserializing behavior of Newtonsoft Json.NET for the various combinations of the Required and NullValueHandling settings. So, I will "ask" for them here and then post an answer shortly. For clarity, these are settings that can be set on the C# class definition, for example:
public class Person
{
[Newtonsoft.Json.JsonProperty("firstname", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public string Firstname { get; set; }
[Newtonsoft.Json.JsonProperty("enabled", Required = Newtonsoft.Json.Required.DisallowNull,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public bool? Enabled { get; set; } = true;
}
The Required and NullValueHandling settings can also be set at the object level using, for example:
[Newtonsoft.Json.JsonObject(ItemRequired=Newtonsoft.Json.Required.Always, ItemNullValueHandling=Newtonsoft.Json.NullValueHandling.Include)]
public class Person
{...}
Or in the case of NullValueHandling, it can also be set in the JsonSerializerSettings provided to the SerializeObject/DeserializeObject calls.
Anyway, how do those settings affect the behavior of the serializing and deserializing when the .Net object property is null and/or when the JSON text being deserialized either gives a null value or is completely missing?
I haven't found a good reference table already posted anywhere.
Based on my testing with Json.NET 13.0.1, this is the behaviour for both serializing and deserializing:
Required | NullValueHandling | Serialize: result if .NET property is null | Deserialize: result if JSON field is missing | Deserialize: result if JSON field is null |
---|---|---|---|---|
Default |
Include |
JSON value is "null" |
property is default | property is null |
Default |
Ignore |
JSON key/value not included | property is default | property is default |
AllowNull |
Include |
JSON value is "null" |
Exception | property is null |
AllowNull |
Ignore |
JSON key/value not included | Exception | property is default |
Always |
Include |
Exception | Exception | Exception |
Always |
Ignore |
JSON key/value not included | Exception | Exception |
DisallowNull |
Include |
Exception | property is default | Exception |
DisallowNull |
Ignore |
JSON key/value not included | property is default | Exception |
A few notes about the results shown above:
"firstname": "null"
For reference, the default values for these settings are: