Serializer options cannot be changed once serialization or deserialization has occurred

Problem

When using System.Text.Json, it’s a good idea to reuse JsonSerializerOptions objects. This leads to a massive 200x speedup in subsequent calls to the serializer.

The downside is you can’t change properties on the options object after you’ve passed it in a Serialize()/Deserialize() call. You’ll get the exception:

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

Solution

This exception reveals an odd API design decision regarding System.Text.Json. Usually things are immutable or not. In this case, JsonSerializerOptions properties are conditionally immutable.

To get around this problem, you’ll need a new JsonSerializerOptions object for each combo of settings you want to use.

For example, the following code serializes a Person object with and without indenting, so it needs two different JsonSerializerOptions objects.

var person = new Person()
{
	Name = "Bobby Fischer"
};
var optionsForHumans = new JsonSerializerOptions()
{
	WriteIndented = true
};
var optionsForComputers = new JsonSerializerOptions()
{
	WriteIndented = false
};

var forHumans = JsonSerializer.Serialize(person, optionsForHumans);

var forComputers = JsonSerializer.Serialize(person, optionsForComputers);
Code language: C# (cs)

Leave a Comment