---
title: "Conventions: Serialization"
url: "https://docs.ravendb.net/6.2/client-api/configuration/serialization"
version: "6.2"
language: "csharp"
---

# Conventions: Serialization

> Client language: C#. Also available for [Java](https://docs.ravendb.net/6.2/client-api/configuration/serialization.java.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> - The C# client serializes entities into JSON using the
>   [Newtonsoft.Json](https://www.newtonsoft.com/json/help/html/SerializingJSON.htm) library (also known as Json.NET).
> - Use the [conventions](https://docs.ravendb.net/6.2/client-api/configuration/conventions.md) 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](#ignoring-a-property)
>   - [CustomizeJsonSerializer](#customizejsonserializer)
>     - [Adding a converter](#adding-a-converter)
>     - [Example: Storing a temperature as a string](#example-storing-a-temperature-as-a-string)
>     - [Example: Storing FHIR resources](#example-storing-fhir-resources)
>   - [JsonContractResolver](#jsoncontractresolver)
>   - [BulkInsert.TrySerializeEntityToJsonStream](#bulkinsert-tryserializeentitytojsonstream)
>   - [IgnoreByRefMembers and IgnoreUnsafeMembers](#ignorebyrefmembers-and-ignoreunsafemembers)

## Ignoring a property {#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.
  ```csharp
  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 {#customizejsonserializer}

- The client uses `JsonSerializer` objects of the [Newtonsoft.Json](https://www.newtonsoft.com/json/help/html/SerializingJSON.htm)
  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](https://docs.ravendb.net/6.2/client-api/configuration/deserialization.md#customizejsondeserializer) convention.
  ```csharp
  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](https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm) 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.
   ```csharp
   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\"");
   }
   ```
   > **Note**
   >
   > 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}`).

```csharp
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.

```csharp
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](https://hl7.org/fhir/) (Fast Healthcare Interoperability Resources) is a standard for exchanging healthcare data,
published by HL7.  
The [Firely .NET SDK](https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/) 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](#adding-a-converter).

```csharp
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.

```csharp
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 {#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.
  ```csharp
  Conventions =
  {
      Serialization = new NewtonsoftJsonSerializationConventions
      {
          JsonContractResolver = new CustomJsonContractResolver()
      }
  }
  ```
  ```csharp
  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.
  ```csharp
  public class CustomizedRavenJsonContractResolver : DefaultRavenContractResolver
  {
      public CustomizedRavenJsonContractResolver(ISerializationConventions conventions) : base(conventions)
      {
      }

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

## BulkInsert.TrySerializeEntityToJsonStream {#bulkinsert-tryserializeentitytojsonstream}

- Adjust [Bulk Insert](https://docs.ravendb.net/6.2/client-api/bulk-insert/how-to-work-with-bulk-insert-operation.md)
  behavior by using the `TrySerializeEntityToJsonStream` convention to register a custom
  serialization implementation.
  ```csharp
  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.
  ```csharp
  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 {#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()`](https://docs.ravendb.net/6.2/client-api/session/saving-changes.md)
  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`

## See also

- [Conventions](https://docs.ravendb.net/6.2/client-api/configuration/conventions.md)
- [Load Balance &amp; Failover](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/overview.md)
- [Deserialization](https://docs.ravendb.net/6.2/client-api/configuration/deserialization.md)
- [Deserialization Security](https://docs.ravendb.net/6.2/client-api/security/deserialization-security.md)
- [Document Identifiers](https://docs.ravendb.net/6.2/client-api/document-identifiers/working-with-document-identifiers.md)
- [Global ID Generation](https://docs.ravendb.net/6.2/client-api/configuration/identifier-generation/global.md)
- [Type-specific ID](https://docs.ravendb.net/6.2/client-api/configuration/identifier-generation/type-specific.md)
- [Document Store](https://docs.ravendb.net/6.2/client-api/what-is-a-document-store.md)
