Skip to content

Commit ca93180

Browse files
authored
Add documentation for CA2026: Prefer JsonElement.Parse over JsonDocument.Parse().RootElement (#49640)
1 parent 0a90a83 commit ca93180

File tree

8 files changed

+129
-2
lines changed

8 files changed

+129
-2
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
---
2+
title: "CA2026: Prefer JsonElement.Parse over JsonDocument.Parse().RootElement"
3+
description: "Learn about code analysis rule CA2026 - Prefer JsonElement.Parse over JsonDocument.Parse().RootElement"
4+
ms.date: 11/05/2025
5+
f1_keywords:
6+
- CA2026
7+
- PreferJsonElementParseOverJsonDocumentParse
8+
helpviewer_keywords:
9+
- CA2026
10+
ai-usage: ai-assisted
11+
dev_langs:
12+
- CSharp
13+
- VB
14+
---
15+
16+
# CA2026: Prefer JsonElement.Parse over JsonDocument.Parse().RootElement
17+
18+
| Property | Value |
19+
|-------------------------------------|--------------------------------------------------------------------------|
20+
| **Rule ID** | CA2026 |
21+
| **Title** | Prefer `JsonElement.Parse` over `JsonDocument.Parse().RootElement` |
22+
| **Category** | [Reliability](reliability-warnings.md) |
23+
| **Fix is breaking or non-breaking** | Non-breaking |
24+
| **Enabled by default in .NET 10** | As suggestion |
25+
26+
## Cause
27+
28+
Code uses `JsonDocument.Parse().RootElement` to parse JSON into a <xref:System.Text.Json.JsonElement>.
29+
30+
## Rule description
31+
32+
<xref:System.Text.Json.JsonElement.Parse*?displayProperty=nameWithType> is more efficient than calling `JsonDocument.Parse().RootElement`. The <xref:System.Text.Json.JsonDocument> type implements <xref:System.IDisposable> and rents arrays from the <xref:System.Buffers.ArrayPool%601>, 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 <xref:System.Text.Json.JsonElement> without these concerns, making it more efficient and less error-prone.
33+
34+
## How to fix violations
35+
36+
Replace calls to `JsonDocument.Parse().RootElement` with `JsonElement.Parse()`.
37+
38+
## Examples
39+
40+
The following code snippet shows a violation of CA2026:
41+
42+
:::code language="csharp" source="snippets/csharp/all-rules/ca2026.cs" id="Violation":::
43+
:::code language="vb" source="snippets/vb/all-rules/ca2026.vb" id="Violation":::
44+
45+
The following code snippet fixes the violation:
46+
47+
:::code language="csharp" source="snippets/csharp/all-rules/ca2026.cs" id="Fixed":::
48+
:::code language="vb" source="snippets/vb/all-rules/ca2026.vb" id="Fixed":::
49+
50+
## When to suppress warnings
51+
52+
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.
53+
54+
## Suppress a warning
55+
56+
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
57+
58+
```csharp
59+
#pragma warning disable CA2026
60+
// The code that's violating the rule is on this line.
61+
#pragma warning restore CA2026
62+
```
63+
64+
To disable the rule for a file, folder, or project, set its severity to `none` in the [configuration file](../configuration-files.md).
65+
66+
```ini
67+
[*.{cs,vb}]
68+
dotnet_diagnostic.CA2026.severity = none
69+
```
70+
71+
For more information, see [How to suppress code analysis warnings](../suppress-warnings.md).
72+
73+
## See also
74+
75+
- [Reliability rules](reliability-warnings.md)
76+
- <xref:System.Text.Json.JsonElement.Parse%2A?displayProperty=nameWithType>
77+
- <xref:System.Text.Json.JsonDocument.Parse%2A?displayProperty=nameWithType>

docs/fundamentals/code-analysis/quality-rules/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ The following table lists code quality analysis rules.
196196
> | [CA2023: Invalid braces in message template](ca2023.md) | The braces present in the message template are invalid. Ensure any braces in the message template are valid opening/closing braces, or are escaped. |
197197
> | [CA2024: Do not use StreamReader.EndOfStream in async methods](ca2024.md) | The property <xref:System.IO.StreamReader.EndOfStream?displayProperty=nameWithType> can cause unintended synchronous blocking when no data is buffered. Instead, use <xref:System.IO.StreamReader.ReadLineAsync?displayProperty=nameWithType> directly, which returns `null` when reaching the end of the stream. |
198198
> | [CA2025: Do not pass `IDisposable` instances into unawaited tasks](ca2025.md) | Unawaited tasks that use `IDisposable` instances might use those instances long after they have been disposed. Ensure tasks using those instances are completed before the instances are disposed. |
199+
> | [CA2026: Prefer JsonElement.Parse over JsonDocument.Parse().RootElement](ca2026.md) | It's more efficient to call `JsonElement.Parse` directly than to call `JsonDocument.Parse().RootElement`. |
199200
> | [CA2100: Review SQL queries for security vulnerabilities](ca2100.md) | A method sets the System.Data.IDbCommand.CommandText property by using a string that is built from a string argument to the method. This rule assumes that the string argument contains user input. A SQL command string that is built from user input is vulnerable to SQL injection attacks. |
200201
> | [CA2101: Specify marshalling for P/Invoke string arguments](ca2101.md) | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. |
201202
> | [CA2109: Review visible event handlers](ca2109.md) | A public or protected event-handling method was detected. Event-handling methods should not be exposed unless absolutely necessary. |

docs/fundamentals/code-analysis/quality-rules/reliability-warnings.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,4 @@ Reliability rules support library and application reliability, such as correct m
3535
| [CA2023: Invalid braces in message template](ca2023.md) | Logging message templates use curly braces `{` and `}` to denote named placeholders for values. Invalid brace usage in message templates can result in runtime exceptions or unexpected logging behavior. |
3636
| [CA2024: Do not use StreamReader.EndOfStream in async methods](ca2024.md) | The property <xref:System.IO.StreamReader.EndOfStream?displayProperty=nameWithType> can cause unintended synchronous blocking when no data is buffered. Instead, use <xref:System.IO.StreamReader.ReadLineAsync?displayProperty=nameWithType> directly, which returns `null` when reaching the end of the stream. |
3737
| [CA2025: Do not pass `IDisposable` instances into unawaited tasks](ca2025.md) | Unawaited tasks that use `IDisposable` instances might use those instances long after they have been disposed. Ensure tasks using those instances are completed before the instances are disposed. |
38+
| [CA2026: Prefer JsonElement.Parse over JsonDocument.Parse().RootElement](ca2026.md) | It's more efficient to call <xref:System.Text.Json.JsonElement.Parse%2A?displayProperty=nameWithType> directly than to call `JsonDocument.Parse().RootElement`. |

docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/all-rules.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net9.0</TargetFramework>
5+
<TargetFramework>net10.0</TargetFramework>
66
<Nullable>enable</Nullable>
77
<RootNamespace>all_rules</RootNamespace>
88
</PropertyGroup>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using System.Text.Json;
2+
3+
namespace ca2026
4+
{
5+
public static class Examples
6+
{
7+
//<Violation>
8+
public static void ProcessJsonViolation(string json)
9+
{
10+
JsonElement element = JsonDocument.Parse(json).RootElement;
11+
//...
12+
}
13+
//</Violation>
14+
15+
//<Fixed>
16+
public static void ProcessJsonFixed(string json)
17+
{
18+
JsonElement element = JsonElement.Parse(json);
19+
//...
20+
}
21+
//</Fixed>
22+
}
23+
}

docs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/all-rules.vbproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
55
<RootNamespace>all_rules</RootNamespace>
6-
<TargetFramework>net9.0</TargetFramework>
6+
<TargetFramework>net10.0</TargetFramework>
77
<NoWarn>$(NoWarn);SYSLIB0050</NoWarn>
88
</PropertyGroup>
99

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
Imports System.Text.Json
2+
3+
Namespace ca2026
4+
5+
Public Module Examples
6+
7+
'<Violation>
8+
Public Sub ProcessJsonViolation(json As String)
9+
Dim element As JsonElement = JsonDocument.Parse(json).RootElement
10+
'...
11+
End Sub
12+
'</Violation>
13+
14+
'<Fixed>
15+
Public Sub ProcessJsonFixed(json As String)
16+
Dim element As JsonElement = JsonElement.Parse(json)
17+
'...
18+
End Sub
19+
'</Fixed>
20+
21+
End Module
22+
23+
End Namespace

docs/navigate/tools-diagnostics/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3347,6 +3347,8 @@ items:
33473347
href: ../../fundamentals/code-analysis/quality-rules/ca2024.md
33483348
- name: CA2025
33493349
href: ../../fundamentals/code-analysis/quality-rules/ca2025.md
3350+
- name: CA2026
3351+
href: ../../fundamentals/code-analysis/quality-rules/ca2026.md
33503352
- name: Security rules
33513353
items:
33523354
- name: Overview

0 commit comments

Comments
 (0)