Skip to main content

Conventions: Serialization

Ignoring a property​

  • By default, RavenDB serializes all properties and all public fields of an entity.
  • Decorate a property with [JsonIgnore] (from the Newtonsoft.Json namespace) to exclude it from serialization.
    The decorated property will not be stored in the document and will not be available for indexing.

    public class Shirt
    {
    public string Id { get; set; }

    // Stored in the document
    public decimal Price { get; set; }

    // Not stored - computed from Price at runtime
    [JsonIgnore]
    public decimal PriceWithTax => Price * 1.2m;
    }

CustomizeJsonSerializer​

  • The client uses JsonSerializer objects of the Newtonsoft.Json library to serialize entities into JSON before sending the entities to the server, and to deserialize documents loaded from the server back into entities.
  • Use the CustomizeJsonSerializer convention to register an action that modifies the JsonSerializer objects.
    The client applies the registered action when storing entities as well as when loading documents into entities.
    To customize only the deserialization of loaded documents, use the CustomizeJsonDeserializer convention.

    Conventions =
    {
    Serialization = new NewtonsoftJsonSerializationConventions
    {
    CustomizeJsonSerializer = serializer => throw new CodeOmitted()
    }
    }

Adding a converter​

To control the JSON form of a specific type (e.g., to store a temperature as the string "30C"), add a converter for this type: a class that tells the JsonSerializer object how to serialize and deserialize the type.
Learn more about converters in the Newtonsoft.Json Custom JsonConverter article.

Define and register a converter as follows:

  1. Define a converter class derived from the library's JsonConverter<T> class, with your type as T.
  2. Override the converter's WriteJson method to write the type's JSON form.
    WriteJson receives a writer (a JsonWriter object) that writes JSON one element at a time, e.g., the writer's WriteValue method writes a single value.

    public override void WriteJson(JsonWriter writer, Temperature value, JsonSerializer serializer)
    {
    // Supported: WriteValue writes the string "30C" as a single JSON value
    writer.WriteValue($"{value.Celsius}C");

    // Not supported: WriteRaw would write "30C" as raw JSON text
    // writer.WriteRaw($"\"{value.Celsius}C\"");
    }

    The writer that the client provides does not support raw JSON text (a JSON string written in one piece), so calling the writer's WriteRaw or WriteRawValue method throws a NotSupportedException.

  3. Override the converter's ReadJson method to convert the JSON form back into the type.
  4. In the action you register using CustomizeJsonSerializer, add the converter to the Converters collection of the JsonSerializer object.

Example: Storing a temperature as a string​

In the following example, a WeatherReport entity holds a Temperature object in its Temp property.
A converter stores the Temperature object as a string (e.g., "30C") rather than as a JSON object (e.g., {"Celsius": 30}).

public class Temperature
{
public int Celsius { get; set; }
}

public class WeatherReport
{
public string Id { get; set; }
public Temperature Temp { get; set; }
}

public class TemperatureConverter : JsonConverter<Temperature>
{
public override void WriteJson(JsonWriter writer, Temperature value, JsonSerializer serializer)
{
writer.WriteValue($"{value.Celsius}C");
}

public override Temperature ReadJson(JsonReader reader, Type objectType, Temperature existingValue,
bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;

// Remove the trailing "C" and parse the number
var text = (string)reader.Value;
return new Temperature { Celsius = int.Parse(text.Substring(0, text.Length - 1)) };
}
}

The following code uses CustomizeJsonSerializer to register the TemperatureConverter class defined above, stores a WeatherReport document, and loads the document back.
Since CustomizeJsonSerializer applies when loading documents as well, the same converter converts the stored string back into a Temperature object.

using (var store = new DocumentStore
{
Urls = new[] { "http://localhost:8080" },
Database = "Demo",
Conventions =
{
Serialization = new NewtonsoftJsonSerializationConventions
{
// Register the converter
CustomizeJsonSerializer = serializer => serializer.Converters.Add(new TemperatureConverter())
}
}
}.Initialize())
{
using (var session = store.OpenSession())
{
// The document is stored with: "Temp": "30C"
session.Store(new WeatherReport { Temp = new Temperature { Celsius = 30 } }, "weatherReports/1");
session.SaveChanges();
}

using (var session = store.OpenSession())
{
// report.Temp is loaded back into a Temperature object with Celsius = 30
var report = session.Load<WeatherReport>("weatherReports/1");
}
}

Example: Storing FHIR resources​

FHIR (Fast Healthcare Interoperability Resources) is a standard for exchanging healthcare data, published by HL7.
The Firely .NET SDK provides .NET classes for FHIR resources (e.g., Patient), along with its own JSON serializer and parser for these classes.

In the following example, a converter hands the serialization of FHIR resources to the SDK's serializer and parser, so a Patient resource is stored in FHIR's JSON format and loaded back into a Patient object.
The converter's WriteJson method writes the serializer's output to the writer element by element, since the writer does not support raw JSON text.

using System;
using System.IO;
// Firely .NET SDK namespaces, from the Hl7.Fhir.R4 NuGet package
using Hl7.Fhir.ElementModel;
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using Newtonsoft.Json;

public class FhirResourceConverter<T> : JsonConverter<T> where T : Base
{
// Skip JSON properties that the SDK's class does not define
// (e.g., the @metadata property of a loaded RavenDB document)
private static readonly PocoBuilderSettings BuilderSettings = new() { IgnoreUnknownMembers = true };

public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
{
// Serialize the resource using the SDK's serializer
var json = new FhirJsonSerializer().SerializeToString(value);

// Write the resulting JSON to the writer element by element,
// keeping dates and decimal values exactly as the SDK wrote them
using (var reader = new JsonTextReader(new StringReader(json))
{ DateParseHandling = DateParseHandling.None, FloatParseHandling = FloatParseHandling.Decimal })
{
writer.WriteToken(reader);
}
}

public override T ReadJson(JsonReader reader, Type objectType, T existingValue,
bool hasExistingValue, JsonSerializer serializer)
{
// Parse the stored JSON into the SDK's class
return FhirJsonNode.Read(reader).ToPoco<T>(BuilderSettings);
}
}

The following code uses CustomizeJsonSerializer to register the converter class defined above for the Patient class (FhirResourceConverter<Patient>), stores a Patient resource as a document, and loads the document back into a Patient object.

using (var store = new DocumentStore
{
Urls = new[] { "http://localhost:8080" },
Database = "Demo",
Conventions =
{
Serialization = new NewtonsoftJsonSerializationConventions
{
// Register a converter for each FHIR resource class you store
CustomizeJsonSerializer = serializer => serializer.Converters.Add(new FhirResourceConverter<Patient>())
}
}
}.Initialize())
{
using (var session = store.OpenSession())
{
var patient = new Patient
{
// The resource ID is used as the document ID;
// FHIR IDs may contain only letters, digits, '-', and '.'
Id = "pat-1001",
Active = true,
Name = new List<HumanName>
{
new HumanName { Family = "Patel", Given = new List<string> { "Sandeep" } }
}
};

session.Store(patient);
session.SaveChanges();
}

using (var session = store.OpenSession())
{
// Loaded back into a Patient object
var patient = session.Load<Patient>("pat-1001");
}
}

JsonContractResolver​

  • The default JsonContractResolver convention used by RavenDB will serialize all properties and all public fields.
  • Change this behavior by providing your own implementation of the IContractResolver interface.

    Conventions =
    {
    Serialization = new NewtonsoftJsonSerializationConventions
    {
    JsonContractResolver = new CustomJsonContractResolver()
    }
    }

    public class CustomJsonContractResolver : IContractResolver
    {
    public JsonContract ResolveContract(Type type)
    {
    throw new CodeOmitted();
    }
    }

  • You can also customize the behavior of the default resolver by inheriting from DefaultRavenContractResolver and overriding specific methods.

    public class CustomizedRavenJsonContractResolver : DefaultRavenContractResolver
    {
    public CustomizedRavenJsonContractResolver(ISerializationConventions conventions) : base(conventions)
    {
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
    throw new CodeOmitted();
    }
    }

BulkInsert.TrySerializeEntityToJsonStream​

  • Adjust Bulk Insert behavior by using the TrySerializeEntityToJsonStream convention to register a custom serialization implementation.

    Conventions =
    {
    BulkInsert =
    {
    TrySerializeEntityToJsonStream = (entity, metadata, writer) => throw new CodeOmitted(),
    }
    }

  • The registered function receives the entity, the entity's metadata, and the writer of the bulk insert stream (a StreamWriter object).
    Return true after writing the entity to the writer as a JSON document, with the entity's metadata under the @metadata property.
    To have the client serialize the entity using the default serialization instead, return false without writing to the writer.

    Conventions =
    {
    BulkInsert =
    {
    TrySerializeEntityToJsonStream = (entity, metadata, writer) =>
    {
    // Let the client serialize entities of other types
    if (entity is not User)
    return false;

    // Convert the entity into a JSON document
    var document = JObject.FromObject(entity);

    // Add the entity's metadata under the @metadata property
    var metadataObject = new JObject();
    foreach (var keyValue in metadata)
    metadataObject.Add(keyValue.Key, new JValue(keyValue.Value));
    document["@metadata"] = metadataObject;

    // Write the document to the bulk insert stream
    var jsonWriter = new JsonTextWriter(writer);
    new JsonSerializer().Serialize(jsonWriter, document);
    jsonWriter.Flush();

    return true;
    }
    }
    }

IgnoreByRefMembers and IgnoreUnsafeMembers​

  • By default, if you try to store an entity with ref or unsafe members, the Client will throw an exception when session.SaveChanges() is called.
  • Set the IgnoreByRefMembers convention to true to simply ignore ref members when an attempt to store an entity with ref members is made.
    The entity will be uploaded to the server with all non-ref members without throwing an exception.
    The document structure on the server-side will not contain fields for those ref members.
  • Set the IgnoreUnsafeMembers convention to true to ignore all pointer members in the same manner.
  • IgnoreByRefMembers default value: false
  • IgnoreUnsafeMembers default value: false

In this article