NET 8 – Mark JsonSerializerOptions as readonly
Starting with .NET 8 you can mark JsonSerializerOptions
instances as read-only, preventing further changes to the instance. To freeze the instance, simply call MakeReadOnly
on the options instance.
Let’s take an example:
var options = new JsonSerializerOptions
{
AllowTrailingCommas = true,
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseUpper,
PreferredObjectCreationHandling = JsonObjectCreationHandling.Populate,
};
options.MakeReadOnly();
Code language: C# (cs)
Furthermore, you can check if an instance was frozen or not by checking the IsReadOnly
property.
options.IsReadOnly
Code language: C# (cs)
Attempting to modify a JsonSerializerOptions
instance after it was marked as read only will result in an InvalidOperationException
:
Unhandled exception. System.InvalidOperationException: This JsonSerializerOptions instance is read-only or has already been used in serialization or deserialization.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerOptionsReadOnly(JsonSerializerContext context)
at System.Text.Json.JsonSerializerOptions.VerifyMutable()
Code language: plaintext (plaintext)
MakeReadOnly(bool populateMissingResolver)
overload
When populateMissingResolver
is passed as true
, the method will go ahead and add the default reflection resolver to your JsonSerializerOptions
when missing. Careful when using this method in trimmed / Native AOT applications as it will root the reflection-related assemblies and include them in your build.
One Comment