Overview

Customizing JSON Contracts

Availability: .NET 7

Modifiers

A modifier is an Action<JsonTypeInfo> or a static void method with a JsonTypeInfo parameter that gets the current state of the contract as an argument and makes modifications to it.

  • Modify the JsonTypeInfo.Get property to change serialization behavior
  • Modify the JsonTypeInfo.Set property to change deserialization behavior
  • Create a new property using JsonTypeInfo.CreateJsonPropertyInfo(Type, String) and add it to the JsonTypeInfo.Properties collection

Modifications

The following modifications can be made:

ModificationApplicable to this JsonTypeInfo.KindHow
Customize a property’s valueJsonTypeInfoKind.ObjectModify the Get or Set delegate of the JsonPropertyInfo object
Add or remove propertiesJsonTypeInfoKind.ObjectAdd or remove items from JsonTypeInfo.Properties list
Conditionally serialize a propertyJsonTypeInfoKind.ObjectModify the JsonPropertyInfo.ShouldSerialize predicate
Customize number handling for a specific typeJsonTypeInfoKind.NoneModify the JsonTypeInfo.NumberHandling value

Process

To customize JSON contracts:

  1. Create modifiers
  2. Create a JsonSerializerOptions instance
  3. In JsonSerializerOptions’s TypeInfoResolver property, set a new DefaultJsonTypeInfoResolver instance
  4. In TypeInfoResolver’s Modifiers property, assign custom actions

Example:

JsonSerializerOptions options = new()
{
    TypeInfoResolver = new DefaultJsonTypeInfoResolver
    {
        Modifiers =
        {
            MyCustomModifier1,
            MyCustomModifier2
        }
    }
};