OdeToCode IC Logo

Serialization Options With Azure DocumentDB

Tuesday, April 28, 2015

DocumentDBBehind the scenes, Azure’s DocumentDB uses Json.NET to serialize objects. Json.NET offers some flexibility in how serialization behaves through a number of serialization settings, but the DocumentDB SDK doesn’t expose these settings.

What if we want to change, say, the  NullValueHandling behavior to ignore null values?

Michalis Zervos offers one solution. Serialize objects using your own code then save the result as a document with the stream based APIs of DocumentDB. This approach gives you the ultimate control over when and how to serialize each object.

Another approach is to use the global default settings of Json.NET.

JsonConvert.DefaultSettings = () =>
{
    return new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    };
};

Being global, you’ll want these settings to apply to all the documents saved into Azure, as well as any other serialization that might be happening in the same application. but it can turn this document:

{
  "Name": "Scott",
  "Medications": null,
  "Procedures": null,
  "id": "c15a4b48-bc7b-4440-a32b-88a9c345f705"
}

.. into this one:

{
  "Name": "Scott",
  "id": "e388eb16-de6f-4de6-9b11-851c2a67ef9e"
}