Serializer options cannot be changed once serialization or deserialization has occurred

By FoxLearn 3/20/2025 2:36:59 AM   52
When using System.Text.Json, it’s highly recommended to reuse JsonSerializerOptions objects, as this provides a significant speed boost (up to 200 times faster) for subsequent serialization and deserialization operations.

However, the downside is that once a JsonSerializerOptions object is passed into a Serialize() or Deserialize() method, you cannot modify its properties afterward. Attempting to do so will result in the following exception:

System.InvalidOperationException: Serializer options cannot be changed once serialization or deserialization has occurred

Solution

This exception points to a somewhat peculiar design choice within the System.Text.Json API. Typically, objects are either immutable or mutable, but in this case, the properties of JsonSerializerOptions are conditionally immutable.

To work around this limitation, you should create a new JsonSerializerOptions instance whenever you need a different set of options. Each combination of settings requires a fresh JsonSerializerOptions object.

For instance, suppose you want to serialize an object with different date formats for two scenarios.

Here’s how you can achieve that with two separate JsonSerializerOptions instances:

var person = new Person()
{
    Name = "Jane Doe",
    BirthDate = new DateTime(1990, 5, 15)
};

var optionsForShortDate = new JsonSerializerOptions()
{
    Converters = { new JsonDateFormatConverter("MM/dd/yyyy") }
};

var optionsForLongDate = new JsonSerializerOptions()
{
    Converters = { new JsonDateFormatConverter("dddd, MMMM dd, yyyy") }
};

var shortDate = JsonSerializer.Serialize(person, optionsForShortDate);
var longDate = JsonSerializer.Serialize(person, optionsForLongDate);

In this example, the JsonSerializerOptions objects are configured to serialize the BirthDate property in different date formats by using separate options for each format.