Cache and reuse 'JsonSerializerOptions' instances
Cache and reuse 'JsonSerializerOptions' instances
Microsoft docsDescription
Using a local instance of System.Text.Json.JsonSerializerOptions for serialization or deserialization can substantially degrade the performance of your application if your code executes multiple times since System.Text.Json internally caches serialization-related metadata into the provided instance.
Cause
A local instance of System.Text.Json.JsonSerializerOptions is used once as the options argument of a System.Text.Json.JsonSerializer.Serialize or System.Text.Json.JsonSerializer.Deserialize call.
How to fix violations
You can use the singleton pattern to avoid creating a new System.Text.Json.JsonSerializerOptions instance every time your code is executed.
Example
static string Serialize<T>(T value)
{
JsonSerializerOptions jsonOptions = new()
{
WriteIndented = true
};
return JsonSerializer.Serialize(value, jsonOptions);
}
static T Deserialize<T>(string json)
{
return JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions { AllowTrailingCommas = true });
}
private static readonly JsonSerializerOptions s_writeOptions = new()
{
WriteIndented = true
};
private static readonly JsonSerializerOptions s_readOptions = new()
{
AllowTrailingCommas = true
};
static string Serialize<T>(T value)
{
return JsonSerializer.Serialize(value, s_writeOptions);
}
static T Deserialize<T>(string json)
{
return JsonSerializer.Deserialize<T>(json, s_readOptions);
}When to suppress
It's safe to suppress this warning if you know that your code will not instantiate a JsonSerializerOptions instance more than once.