Skip to main content

How to Copy a JsonElement into a Utf8JsonWriter with WriteTo in C#

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

weather.WriteTo(writer) writes the whole weather JSON object, every property inside it included, into a Utf8JsonWriter. It's how you put JSON you already have inside new JSON you're writing.

Microsoft's reference: Writes the element to the specified writer as a JSON value. A Utf8JsonWriter writes JSON piece by piece, here into a MemoryStream.

Syntax​

Syntax
using System.Text.Json;

using Utf8JsonWriter <writer> = new(<stream>);

<writer>.WriteStartObject();
<writer>.WritePropertyName("<name>");
<element>.WriteTo(<writer>);
<writer>.WriteEndObject();
PartWhat it is
Utf8JsonWriterWrites JSON, piece by piece, into a stream
WritePropertyName("<name>")Writes a property name. The next value written becomes its value
<element>.WriteTo(<writer>)Writes the element, and everything inside it, as one JSON value

The Example​

A console app called JsonWriteTo parses a small weather object, then writes a new object that holds a source string and the whole weather object.

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 JsonWriteTo
cd JsonWriteTo
Output
The template "Console App" was created successfully.

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

dotnet new console -n JsonWriteTo creates a folder named JsonWriteTo 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 JsonWriteTo.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the JSON that already exists:

Program.cs (the existing JSON)
using System.Text;
using System.Text.Json;

using JsonDocument document = JsonDocument.Parse("""{"city":"Oslo","temperature":4}""");
JsonElement weather = document.RootElement;

JsonDocument.Parse reads the text, and RootElement is the object at its top.

Then the new JSON, written into memory:

Program.cs (writing new JSON)
using MemoryStream stream = new();
using (Utf8JsonWriter writer = new(stream, new JsonWriterOptions { Indented = true }))
{
writer.WriteStartObject();
writer.WriteString("source", "example");
writer.WritePropertyName("weather");

// Copies the element, with everything inside it, into the writer.
weather.WriteTo(writer);

writer.WriteEndObject();
}
  • Indented = true writes the JSON over several lines. The reference: Gets or sets a value that indicates whether the Utf8JsonWriter should format the JSON output, which includes indenting nested JSON tokens, adding new lines, and adding white space between property names and values.
  • WritePropertyName("weather") writes the name that WriteTo then gives a value.
  • The using block disposes the writer at its closing brace. The reference for Dispose: Commits any leftover JSON text that has not yet been flushed and releases all resources used by the current instance.

Then print the bytes as text:

Program.cs (printing it)
Console.WriteLine(Encoding.UTF8.GetString(stream.ToArray()));

Step 3: Run It​

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

Terminal
dotnet run
Output
{
"source": "example",
"weather": {
"city": "Oslo",
"temperature": 4
}
}

macOS-style terminal window titled Terminal — JsonWriteTo showing dotnet run printing an indented JSON object with a source of example and a weather object that holds the city Oslo and a temperature of 4

The weather object came through whole, with its two properties, as the value of weather.

The Complete File​

macOS-style code window titled Program.cs — JsonWriteTo showing a JsonDocument parsed from a small weather object, a Utf8JsonWriter with indented output that writes an object with a source string and a weather property filled by WriteTo, and a line that prints the bytes as text

Program.cs
using System.Text;
using System.Text.Json;

using JsonDocument document = JsonDocument.Parse("""{"city":"Oslo","temperature":4}""");
JsonElement weather = document.RootElement;

using MemoryStream stream = new();
using (Utf8JsonWriter writer = new(stream, new JsonWriterOptions { Indented = true }))
{
writer.WriteStartObject();
writer.WriteString("source", "example");
writer.WritePropertyName("weather");

// Copies the element, with everything inside it, into the writer.
weather.WriteTo(writer);

writer.WriteEndObject();
}

Console.WriteLine(Encoding.UTF8.GetString(stream.ToArray()));

Common Mistakes​

MistakeWhat happensDo this instead
Reading the stream before the writer has flushedThe JSON stays inside the writer: after writing an object, the stream held 0 bytes until Flush(), and then 15Call Flush(), or dispose the writer as the example's using block does, before you read the stream. The reference for Flush: Commits the JSON text written so far, which makes it visible to the output destination.
Writing a value inside an object without a property nameWriteTo straight after WriteStartObject() threw InvalidOperationException: Cannot write the start of an object or array without a property name. Current token type is 'StartObject'.Call WritePropertyName first

FAQ​

Why does the writer throw instead of writing the JSON?​

It refuses to write JSON that isn't valid. The reference: A method that attempts to write invalid JSON when validation is enabled throws an InvalidOperationException with a context-specific error message.

Conclusion​

JsonElement.WriteTo writes an existing JSON value into a Utf8JsonWriter in one call, nested properties included. Give it a property name first when you're inside an object, and flush or dispose the writer before you read what it wrote.

Additional Resources​