Редактиране

Споделяне чрез


CA1869: Cache and reuse 'JsonSerializerOptions' instances

Property Value
Rule ID CA1869
Title Cache and reuse 'JsonSerializerOptions' instances
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 As suggestion

Cause

A local instance of JsonSerializerOptions is used once as the options argument of a Serialize or Deserialize call.

Rule description

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 violations

You can use the singleton pattern to avoid creating a new JsonSerializerOptions instance every time your code is executed.

Example

The 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.

When to suppress warnings

It's safe to suppress this warning if you know that your code will not instantiate a JsonSerializerOptions instance more than once.

Suppress a warning

If 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.