A local instance of JsonSerializerOptions is used once as the options
argument of a Serialize or Deserialize call.
Using a local instance of 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.
How to fix violationsYou can use the singleton pattern to avoid creating a new JsonSerializerOptions instance every time your code is executed.
ExampleThe following code snippet shows two violations of CA1869:
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 });
}
The following code snippet fixes the violations:
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);
}
If there are further calls to Serialize
or Deserialize
, s_writeOptions
or s_readOptions
should be reused, respectively.
It's safe to suppress this warning if you know that your code will not instantiate a JsonSerializerOptions instance more than once.
Suppress a warningIf you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA1869
// The code that's violating the rule is on this line.
#pragma warning restore CA1869
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1869.severity = none
For more information, see How to suppress code analysis warnings.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4