This project has moved and is read-only. For the latest updates, please go here.

JsonSerializer and Null Value Handling

Jun 7, 2010 at 11:21 AM
Edited Jun 7, 2010 at 11:25 AM


I'm currently working on a project where we need to do a bit of massaging of the first level of properties (the property names vary at runtime).
The remote end also requires that null values are given special values, instead of a standard null value.
I have JsonConverters for each of the types I need to serialize.

When I use JsonConvert - these JsonConverters are called for any null values.

However, using JsonSerializer, the JsonConverters are not called if the value passed to Serializer.Serialize is null.

The (possibly hacky) workaround that I have at the moment is something like this:

            if (PropertyValue == null)
                foreach (JsonConverter converter in Serializer.Converters)
                    if (converter.CanConvert(Property.PropertyType))
                        converter.WriteJson(Writer, PropertyValue, Serializer);
            // else, let the serializer do the work:
            Serializer.Serialize(Writer, PropertyValue);

Is there another, better way of doing this?