overview
System.Text.Jsoncreates a JSON contract for each .NET type that determines how it is serialized and deserialized.- The contract is created based on the shape of the type — its properties, fields and interfaces it implements.
- Types are mapped to contracts either at run time (via reflection) or compile time (via source generation).
- Documentation: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/custom-contracts
customizing json contracts
ℹ️ Important
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.Getproperty to change serialization behavior - Modify the
JsonTypeInfo.Setproperty to change deserialization behavior - Create a new property using
JsonTypeInfo.CreateJsonPropertyInfo(Type, String)and add it to theJsonTypeInfo.Propertiescollection
modifications
The following modifications can be made:
| Modification | Applicable to this JsonTypeInfo.Kind | How |
|---|---|---|
| Customize a property’s value | JsonTypeInfoKind.Object | Modify the Get or Set delegate of the JsonPropertyInfo object |
| Add or remove properties | JsonTypeInfoKind.Object | Add or remove items from JsonTypeInfo.Properties list |
| Conditionally serialize a property | JsonTypeInfoKind.Object | Modify the JsonPropertyInfo.ShouldSerialize predicate |
| Customize number handling for a specific type | JsonTypeInfoKind.None | Modify the JsonTypeInfo.NumberHandling value |
process
To customize JSON contracts:
- Create modifiers
- Create a
JsonSerializerOptionsinstance - In
JsonSerializerOptions’sTypeInfoResolverproperty, set a newDefaultJsonTypeInfoResolverinstance - In
TypeInfoResolver’sModifiersproperty, assign custom actions
Example:
JsonSerializerOptions options = new()
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers =
{
MyCustomModifier1,
MyCustomModifier2
}
}
};