Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Utf8JsonWriter — sequential UTF-8 JSON writing

Utf8JsonWriter in System.Text.Json lets you manually write JSON as UTF-8 bytes to a Stream or IBufferWriter<byte>. You control property order and document structure, while the writer handles JSON syntax and string escaping.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

using var writer = new Utf8JsonWriter(destination, new JsonWriterOptions { Indented = false });
writer.WriteStartObject();
writer.WriteString("name", "Ada");
writer.WriteEndObject();
writer.Flush();

Utf8JsonWriter in the System.Text.Json namespace is a low-level mechanism for sequentially writing JSON as UTF-8 bytes to a Stream or IBufferWriter<byte>. Rather than automatically serializing an entire object, you explicitly write its properties and values. It is useful for building custom serializers; it is not an editable document tree.

Calls to WriteStartObject() and WriteEndObject() delimit an object. WriteString("name", "Ada") writes a name–value pair, whereas WriteStringValue("csharp") writes only a value, such as an array element. WriteStartArray("tags") starts an array property, which WriteEndArray() closes. String-writing methods handle required escaping—do not construct JSON by concatenating text.

By default, output is compact and structural validation is enabled; an invalid operation sequence can cause an InvalidOperationException. JsonWriterOptions lets you configure settings including Indented and SkipValidation. Disabling validation transfers responsibility for structural correctness to the calling code.

Before reading the result, call Flush() to commit pending bytes to the destination. This does not replace closing objects and arrays with the appropriate methods. Use using to dispose the writer. In the example, Encoding.UTF8.GetString(...) converts the written bytes to text solely for display. The APIs used are available in .NET 10 and do not require preview language features.

Examples

using System;
using System.IO;
using System.Text;
using System.Text.Json;

using var stream = new MemoryStream();
using var writer = new Utf8JsonWriter(stream);

writer.WriteStartObject();
writer.WriteString("name", "Ada");
writer.WriteNumber("score", 42);
writer.WriteStartArray("tags");
writer.WriteStringValue("csharp");
writer.WriteStringValue("json");
writer.WriteEndArray();
writer.WriteEndObject();
writer.Flush();

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

Result

{"name":"Ada","score":42,"tags":["csharp","json"]}

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources