Skip to main content

How to Keep a JsonElement After Its Document Is Gone with Clone in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

A JsonElement lives inside its JsonDocument and stops working when that document is disposed. Call Clone() on it while the document is still open, and the copy keeps working for as long as you need it.

Microsoft's reference for the method: Gets a JsonElement that can be safely stored beyond the lifetime of the original JsonDocument.

The document itself has to be disposed. The JSON DOM guide: JsonDocument builds an in-memory view of the data into a pooled buffer. Therefore the JsonDocument type implements IDisposable and needs to be used inside a using block. And its elements go with it: After a JsonDocument instance is disposed, you lose access to all of its JsonElement instances also. To retain access to a JsonElement instance, make a copy of it before the parent JsonDocument instance is disposed. To make a copy, call JsonElement.Clone.

Syntax​

Syntax
using System.Text.Json;

JsonElement <copy> = <element>.Clone();
PartWhat it is
<element>A JsonElement from a JsonDocument that isn't disposed yet, such as document.RootElement or one of its properties
.Clone()The method, declared as public System.Text.Json.JsonElement Clone();. It takes no arguments
<copy>The copy: a JsonElement with the same JSON, which keeps working after the document is disposed

Call it while the document is open: on an element whose document is already disposed, Clone() throws, as Common Mistakes shows.

The Example​

A console app called JsonElementClone reads three saved games, one line of JSON each, with a player's name and their best game. It keeps each player's best game in a list, then reads the scores once every document is gone.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n JsonElementClone
cd JsonElementClone
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/JsonElementClone/JsonElementClone.csproj:
Determining projects to restore...
Restored /Users/you/source/JsonElementClone/JsonElementClone.csproj (in 41 ms).
Restore succeeded.

dotnet new console -n JsonElementClone creates a folder named JsonElementClone with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or JsonElementClone.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First, the saved games:

Program.cs (the saved games)
using System.Text.Json;

// Three saved games, one line of JSON each.
string[] lines =
[
"""{"player":"Ana","best":{"score":420,"level":3}}""",
"""{"player":"Ben","best":{"score":515,"level":4}}""",
"""{"player":"Cara","best":{"score":390,"level":2}}"""
];

Each line is a raw string literal: everything between the two """ is text, so the quotes inside need no escaping. The square brackets around the three lines make them an array.

Then keep each best game:

Program.cs (keep each best game)
List<JsonElement> bestGames = [];
foreach (string line in lines)
{
// Each document is disposed at the end of its pass through the loop.
using JsonDocument document = JsonDocument.Parse(line);
JsonElement best = document.RootElement.GetProperty("best");

// Clone copies the element, so the list can keep it after the document is gone.
bestGames.Add(best.Clone());
}

JsonDocument.Parse(line) reads one line into a document, and GetProperty("best") finds the best object in it. The using in front of the declaration disposes the document when the pass through the loop ends. The using statement reference: When declared in a using declaration, a local variable is disposed at the end of the scope in which it's declared. So best.Clone() runs while the document is still open, and the list gets the copy.

Last, read the copies:

Program.cs (read the copies)
// All three documents are disposed now, and the clones still work.
foreach (JsonElement game in bestGames)
{
int score = game.GetProperty("score").GetInt32();
int level = game.GetProperty("level").GetInt32();
Console.WriteLine($"Score {score}, level {level}: {game.GetRawText()}");
}

GetInt32() reads a JSON number as an int, and GetRawText() gives the element's JSON as text.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Score 420, level 3: {"score":420,"level":3}
Score 515, level 4: {"score":515,"level":4}
Score 390, level 2: {"score":390,"level":2}

macOS-style terminal window titled Terminal — JsonElementClone showing dotnet run printing Score 420, level 3, then Score 515, level 4, then Score 390, level 2, each followed by that best game's JSON

By the time the second loop ran, all three documents were disposed, and every copy still worked: the scores 420, 515 and 390, the levels 3, 4 and 2, and each best game's JSON.

The Complete File​

macOS-style code window titled Program.cs — JsonElementClone showing three saved-game JSON lines in an array, a loop that parses each line in a using declaration, finds its best property and adds best.Clone() to a list, and a second loop that reads score and level from each copy and prints them with the copy's JSON

Program.cs
using System.Text.Json;

// Three saved games, one line of JSON each.
string[] lines =
[
"""{"player":"Ana","best":{"score":420,"level":3}}""",
"""{"player":"Ben","best":{"score":515,"level":4}}""",
"""{"player":"Cara","best":{"score":390,"level":2}}"""
];

List<JsonElement> bestGames = [];
foreach (string line in lines)
{
// Each document is disposed at the end of its pass through the loop.
using JsonDocument document = JsonDocument.Parse(line);
JsonElement best = document.RootElement.GetProperty("best");

// Clone copies the element, so the list can keep it after the document is gone.
bestGames.Add(best.Clone());
}

// All three documents are disposed now, and the clones still work.
foreach (JsonElement game in bestGames)
{
int score = game.GetProperty("score").GetInt32();
int level = game.GetProperty("level").GetInt32();
Console.WriteLine($"Score {score}, level {level}: {game.GetRawText()}");
}

Common Mistakes​

MistakeWhat happensDo this instead
Keeping the element itself: bestGames.Add(document.RootElement.GetProperty("best"))Reading it after the loop threw ObjectDisposedException: Cannot access a disposed object. with Object name: 'JsonDocument'.Keep the copy: bestGames.Add(best.Clone())
Calling Clone() after the document is disposedbest.Clone() after the using block threw the same ObjectDisposedException: Cannot access a disposed object.Call Clone() inside the using block, while the document is open
Returning document.RootElement.GetProperty("best") from a method that parses with usingThe caller's read threw the same ObjectDisposedException: the document was disposed when the method returnedReturn document.RootElement.GetProperty("best").Clone(): the caller read score 420. The guide: If you return the RootElement or a sub-element directly without making a Clone, the caller won't be able to access the returned JsonElement after the JsonDocument that owns it is disposed.

FAQ​

Does a clone of a clone use more memory?​

No. A check measured the bytes each call allocated with GC.GetAllocatedBytesForCurrentThread(): the first Clone() allocated 216 bytes, and Clone() on that copy allocated 0 bytes. The method's reference: If this JsonElement is itself the output of a previous call to Clone or a value contained within another JsonElement that was the output of a previous call to Clone, this method results in no additional memory allocation.

Can I get a JsonElement without a JsonDocument?​

Yes, from .NET 10. JsonElement.Parse reads JSON straight into an element, with no document to dispose. Its reference: Parses text representing a single JSON value into a JsonElement. The same loop with JsonElement.Parse kept both best games without Clone():

JsonElement.Parse instead of a document
// JsonElement.Parse returns an element with no JsonDocument to dispose.
List<JsonElement> bestGames = [];
foreach (string line in lines)
{
bestGames.Add(JsonElement.Parse(line).GetProperty("best"));
}
Output
{"score":420,"level":3}
{"score":515,"level":4}

The code analysis rule CA2026 explains why it's preferred over JsonDocument.Parse().RootElement: The JsonDocument type implements IDisposable and rents arrays from the ArrayPool<T>, 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.

Conclusion​

A JsonElement works only while its JsonDocument is open. Call Clone() before the document is disposed, whether you keep the element in a list or return it from a method, and the copy keeps working, while a clone of a clone costs no more memory. From .NET 10, JsonElement.Parse gives an element with no document to dispose at all.

Additional Resources​