Serializer options cannot be changed once serialization or deserialization has occurred
By FoxLearn 3/20/2025 2:36:59 AM 52
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.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization