Conventions: Serialization
- The C# client serializes entities into JSON using the Newtonsoft.Json library (also known as Json.NET).
- Use the conventions described in this article to customize the serialization (e.g., to exclude a property, or to control the JSON form of a type).
- In this article:
Ignoring a property
- By default, RavenDB serializes all properties and all public fields of an entity.
- Decorate a property with
[JsonIgnore](from theNewtonsoft.Jsonnamespace) 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 documentpublic decimal Price { get; set; }// Not stored - computed from Price at runtime[JsonIgnore]public decimal PriceWithTax => Price * 1.2m;}
CustomizeJsonSerializer
- The client uses
JsonSerializerobjects 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
CustomizeJsonSerializerconvention to register an action that modifies theJsonSerializerobjects.
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:
- Define a converter class derived from the library's
JsonConverter<T>class, with your type asT. - Override the converter's
WriteJsonmethod to write the type's JSON form.
WriteJsonreceives a writer (aJsonWriterobject) that writes JSON one element at a time, e.g., the writer'sWriteValuemethod writes a single value.
public override void WriteJson(JsonWriter writer, Temperature value, JsonSerializer serializer){// Supported: WriteValue writes the string "30C" as a single JSON valuewriter.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
WriteRaworWriteRawValuemethod throws aNotSupportedException. - Override the converter's
ReadJsonmethod to convert the JSON form back into the type. - In the action you register using
CustomizeJsonSerializer, add the converter to theConverterscollection of theJsonSerializerobject.
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
JsonContractResolverconvention used by RavenDB will serialize all properties and all public fields. - Change this behavior by providing your own implementation of the
IContractResolverinterface.
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
DefaultRavenContractResolverand 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
TrySerializeEntityToJsonStreamconvention 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
StreamWriterobject).
Returntrueafter writing the entity to the writer as a JSON document, with the entity's metadata under the@metadataproperty.
To have the client serialize the entity using the default serialization instead, returnfalsewithout writing to the writer.
Conventions ={BulkInsert ={TrySerializeEntityToJsonStream = (entity, metadata, writer) =>{// Let the client serialize entities of other typesif (entity is not User)return false;// Convert the entity into a JSON documentvar document = JObject.FromObject(entity);// Add the entity's metadata under the @metadata propertyvar 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 streamvar 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
refor unsafe members, the Client will throw an exception whensession.SaveChanges()is called. - Set the
IgnoreByRefMembersconvention totrueto simply ignorerefmembers when an attempt to store an entity withrefmembers is made.
The entity will be uploaded to the server with all non-refmembers without throwing an exception.
The document structure on the server-side will not contain fields for thoserefmembers. - Set the
IgnoreUnsafeMembersconvention totrueto ignore all pointer members in the same manner. IgnoreByRefMembersdefault value:falseIgnoreUnsafeMembersdefault value:false