1

Closed

No chance to customize 'null' when Custom JsonConverterAttribute(Type) is specified

description

Hello,
 
I would like the chance to customize the "null" value that gets written whenever my JsonConverter is specified. However, JsonConverter.WriteJson() is never called when a property value is null.
 
The problem seems to be related to Line 103 in:
Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs
 
  JsonConverter converter = (member != null) ? member.Converter : null;
 
  if (value == null)
  {
    writer.WriteNull();
    return;
  }
 
My motivation for customizing "null" is to do the following:
 
 
[Flags]
public enum Animals{
   Cats = 0x01,
   Dogs = 0x02,
   Fish = 0x04
}
 
public class Person {
    [JsonConverter(typeof(MySpeicalConverter))
    public Animals? Pets{ get; set; }
}
 
 
The JSON output of Person without any Pets would "{ Pets: null }". However, I'd prefer the output to be "{ Pets: [] }" so that it can more easily be used with KnockoutJS' "checked:" binding. However, doing so requires special handling by my converter to process 'null.'
 
Specifically, KO has two distinct behaviors when "checked:" is bound to "null" and "[]". When a checkbox is bound to "checked: null", KO writes "true/false" in the viewModel. When a checkbox is bound to "checked: []", KO pushes checkbox value attributes onto an array.
 
I know this is a really specific edge case, but as a user of the JsonConverter's API, I was expecting to be able to handle null in my JsonConverter.
 
This person also had a similar experience when trying to process "null" in his JsonConverter:
http://stackoverflow.com/questions/8833961/serializing-null-in-json-net
Closed Apr 16, 2012 at 9:52 PM by JamesNK
JsonConverters work with the value type which unfortunately means customizing null isn't possible, and its too late to change now.

comments