Prefer JsonElement.Parse over JsonDocument.Parse().RootElement
Prefer JsonElement.Parse over JsonDocument.Parse().RootElement
Microsoft docsDescription
System.Text.Json.JsonElement.Parse is more efficient than calling JsonDocument.Parse().RootElement. The System.Text.Json.JsonDocument type implements System.IDisposable and rents arrays from the System.Buffers.ArrayPool1, 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 System.Text.Json.JsonElement without these concerns, making it more efficient and less error-prone.
Cause
Code uses JsonDocument.Parse().RootElement to parse JSON into a System.Text.Json.JsonElement.
How to fix violations
Replace calls to JsonDocument.Parse().RootElement with JsonElement.Parse().
Example
#pragma warning disable CA2026
// The code that's violating the rule is on this line.
#pragma warning restore CA2026When to suppress
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.