CKTIS / C#
Utf8JsonReader — reading JSON tokens from UTF-8
Utf8JsonReader in System.Text.Json reads UTF-8 JSON bytes one token at a time, moving only forward. It lets you select values without building a document tree or deserializing the document into objects.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
var reader = new Utf8JsonReader(utf8Json);
while (reader.Read())
{
// Inspect reader.TokenType and read the current token's value.
}Utf8JsonReader is a mutable ref struct in System.Text.Json, available in .NET 10. It accepts ReadOnlySpan<byte> or ReadOnlySequence<byte>. It does not build a document tree; calling code interprets successive tokens and the JSON structure itself.
Read() advances to the next token, and TokenType identifies its kind. Methods such as GetInt32() read the current value without advancing the reader. Check the token kind before calling them; a number must also fit the target type. ValueTextEquals() compares a name or text while accounting for JSON escape sequences, without creating an intermediate string.
The reader cannot be stored in a class field or kept across an await boundary. Pass it by ref to a helper that must advance the original reader; a copy has an independent position. For multisegment input, check HasValueSequence before choosing ValueSequence or ValueSpan.
The constructor in the example assumes a complete document. For chunked input, use isFinalBlock, preserve CurrentState and the unconsumed bytes identified by BytesConsumed, then construct a new reader after supplying more data. The state alone does not retain those bytes. When Read() detects a JSON syntax error, it throws JsonException. However, it can recognize a quoted string as a token even if its contents contain malformed UTF-8. Decoding that token with GetString() can throw InvalidOperationException rather than JsonException. Comments and trailing commas are disallowed by default.
Examples
using System;
using System.Text.Json;
ReadOnlySpan<byte> json = "{\"name\":\"Ada\",\"age\":25}"u8;
var reader = new Utf8JsonReader(json);
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.PropertyName &&
reader.ValueTextEquals("age"u8))
{
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
throw new JsonException("Expected a number.");
Console.WriteLine(reader.GetInt32());
}
}
Result
25
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.