Language
Edit

CA2026: Prefer JsonElement.Parse over JsonDocument.Parse().RootElement

Property Value
Rule ID CA2026
Title Prefer JsonElement.Parse over JsonDocument.Parse().RootElement
Category Reliability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 10 As suggestion
Applicable languages C# and Visual Basic

Cause

Code uses JsonDocument.Parse().RootElement to parse JSON into a JsonElement.

Rule description

JsonElement.Parse is more efficient than calling JsonDocument.Parse().RootElement. The JsonDocument type implements IDisposable and rents arrays from the ArrayPool, which can lead to memory leaks or increased GC pressure if you don't properly dispose the document. The JsonElement.Parse method, introduced in .NET 10, parses JSON directly into a JsonElement without these concerns, making it more efficient and less error-prone.

How to fix violations

Replace calls to JsonDocument.Parse().RootElement with JsonElement.Parse().

Examples

The following code snippet shows a violation of CA2026:

public static void ProcessJsonViolation(string json)
{
    JsonElement element = JsonDocument.Parse(json).RootElement;
    //...
}
Public Sub ProcessJsonViolation(json As String)
    Dim element As JsonElement = JsonDocument.Parse(json).RootElement
    '...
End Sub

The following code snippet fixes the violation:

public static void ProcessJsonFixed(string json)
{
    JsonElement element = JsonElement.Parse(json);
    //...
}
Public Sub ProcessJsonFixed(json As String)
    Dim element As JsonElement = JsonElement.Parse(json)
    '...
End Sub

When to suppress warnings

Don't suppress warnings from this rule. If you're targeting .NET 10 or later, you should use JsonElement.Parse() for better performance and resource management.

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 CA2026
// The code that's violating the rule is on this line.
#pragma warning restore CA2026

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA2026.severity = none

For more information, see How to suppress code analysis warnings.

See also