Table of Contents

Struct JsonReader

Namespace
Nerdbank.Json
Assembly
Nerdbank.Json.dll

Reads JSON values from a UTF-8 byte buffer.

public ref struct JsonReader
Inherited Members

Remarks

String boundaries, escapes, and unescaped control bytes are checked, but Unicode well-formedness is not. CLR strings use UTF-8 replacement fallback and preserve each escaped UTF-16 code unit. Unescaped byte views and raw JSON preserve the original bytes, including invalid UTF-8.

Constructors

JsonReader(scoped in ReadOnlySequence<byte>, bool, JsonCommentHandling)

Initializes a new instance of the JsonReader struct over a possibly segmented UTF-8 document.

public JsonReader(scoped in ReadOnlySequence<byte> jsonUtf8, bool allowTrailingCommas = false, JsonCommentHandling commentHandling = JsonCommentHandling.Disallow)

Parameters

jsonUtf8 ReadOnlySequence<byte>

The UTF-8 document.

allowTrailingCommas bool

Whether trailing commas are accepted.

commentHandling JsonCommentHandling

The policy for JSON comments.

Remarks

The input is borrowed for the lifetime of the reader. Only individual tokens that span segments may be copied.

JsonReader(byte[], bool, JsonCommentHandling)

Initializes a new instance of the JsonReader struct over a borrowed array.

public JsonReader(byte[] jsonUtf8, bool allowTrailingCommas = false, JsonCommentHandling commentHandling = JsonCommentHandling.Disallow)

Parameters

jsonUtf8 byte[]

The borrowed UTF-8 document.

allowTrailingCommas bool

Whether trailing commas are accepted.

commentHandling JsonCommentHandling

The policy for JSON comments.

JsonReader(ReadOnlyMemory<byte>, bool, JsonCommentHandling)

Initializes a new instance of the JsonReader struct over borrowed memory.

public JsonReader(ReadOnlyMemory<byte> jsonUtf8, bool allowTrailingCommas = false, JsonCommentHandling commentHandling = JsonCommentHandling.Disallow)

Parameters

jsonUtf8 ReadOnlyMemory<byte>

The borrowed UTF-8 document.

allowTrailingCommas bool

Whether trailing commas are accepted.

commentHandling JsonCommentHandling

The policy for JSON comments.

JsonReader(ReadOnlySpan<byte>, bool, JsonCommentHandling)

Initializes a new instance of the JsonReader struct.

public JsonReader(ReadOnlySpan<byte> jsonUtf8, bool allowTrailingCommas = false, JsonCommentHandling commentHandling = JsonCommentHandling.Disallow)

Parameters

jsonUtf8 ReadOnlySpan<byte>

The UTF-8 JSON bytes to read from.

allowTrailingCommas bool

A value indicating whether trailing commas should be accepted while reading arrays and objects.

commentHandling JsonCommentHandling

The policy for handling comments during deserialization.

Properties

Consumed

Gets the number of bytes consumed.

public readonly long Consumed { get; }

Property Value

long

End

Gets a value indicating whether all input bytes have been consumed.

public readonly bool End { get; }

Property Value

bool

IsNull

Gets a value indicating whether the next significant byte starts a null literal.

public bool IsNull { get; }

Property Value

bool

NextCode

Gets the first byte of the next significant token, skipping whitespace and permitted comments.

public byte NextCode { get; }

Property Value

byte

Exceptions

FormatException

There is no next token.

NextJsonType

Gets the kind indicated by the next value's first significant byte.

public JsonValueKind NextJsonType { get; }

Property Value

JsonValueKind

Remarks

Inspection does not validate the whole value. Container terminators and separators are not values.

Position

Gets the current position within Sequence.

public SequencePosition Position { get; }

Property Value

SequencePosition

Sequence

Gets the original input sequence.

public ReadOnlySequence<byte> Sequence { get; }

Property Value

ReadOnlySequence<byte>

Remarks

For span-based readers, the first access copies the input into a sequence, which is cached for later accesses.

Methods

Clone(scoped in ReadOnlySequence<byte>)

Creates a reader over different input using this reader's syntax options.

public readonly JsonReader Clone(scoped in ReadOnlySequence<byte> jsonUtf8)

Parameters

jsonUtf8 ReadOnlySequence<byte>

The new borrowed input.

Returns

JsonReader

A reader at the beginning of the new input, with no inherited navigation state.

CreatePeekReader()

Creates an independent copy of this reader at the current position.

public readonly JsonReader CreatePeekReader()

Returns

JsonReader

A copy of this reader positioned at the same location.

Remarks

Advancing the returned reader does not affect this instance. Segmented readers copy only their small navigation state, never the input payload.

EnsureFullyConsumed()

Verifies that the entire input has been consumed except for insignificant whitespace.

public void EnsureFullyConsumed()

ReadBase64Bytes()

Reads a base64-encoded JSON string value that may be null.

public byte[]? ReadBase64Bytes()

Returns

byte[]

The decoded bytes, or null when the next token is a JSON null literal.

ReadBoolean()

Reads a required JSON boolean literal.

public bool ReadBoolean()

Returns

bool

The boolean value that was read.

ReadByte()

Reads a JSON number as an unsigned 8-bit integer.

public byte ReadByte()

Returns

byte

The parsed value.

ReadChar()

Reads a JSON string that must contain exactly one character.

public char ReadChar()

Returns

char

The character encoded in the JSON string.

ReadDecimal()

Reads a JSON number as a decimal value.

public decimal ReadDecimal()

Returns

decimal

The parsed value.

ReadDouble()

Reads a JSON number as a finite double-precision floating-point value.

public double ReadDouble()

Returns

double

The parsed value.

ReadEndArray()

Reads the closing token for a JSON array.

public void ReadEndArray()

ReadInt16()

Reads a JSON number as a signed 16-bit integer.

public short ReadInt16()

Returns

short

The parsed value.

ReadInt32()

Reads a JSON number as a signed 32-bit integer.

public int ReadInt32()

Returns

int

The parsed value.

ReadInt64()

Reads a JSON number as a signed 64-bit integer.

public long ReadInt64()

Returns

long

The parsed value.

ReadNameSeparator()

Reads the name/value separator between a JSON property name and value.

public void ReadNameSeparator()

ReadNull()

Reads a required JSON null literal.

public void ReadNull()

Exceptions

FormatException

The next value is not null.

ReadNumberToken()

Reads the next JSON number token without converting it to a numeric type.

public string ReadNumberToken()

Returns

string

The raw number token as text.

ReadRaw(SerializationContext)

Reads the next JSON value as exact UTF-8 bytes using the active operation's limits.

public RawJson ReadRaw(SerializationContext context)

Parameters

context SerializationContext

The active depth and cancellation limits.

Returns

RawJson

A borrowed sequence slice, or an owned copy when this reader was constructed from a span.

Remarks

Borrowed results must not outlive the input buffers. Use ToOwned() to retain them.

ReadRaw(long)

Reads exactly the specified number of bytes as one complete JSON value.

public RawJson ReadRaw(long length)

Parameters

length long

The byte length, including any surrounding whitespace.

Returns

RawJson

The exact bytes, borrowed for sequence input and owned for span input.

Remarks

Validates with the default depth limit. Use ReadRaw(SerializationContext) to preserve active operation limits.

Exceptions

ArgumentOutOfRangeException

The length is negative or exceeds the remaining input.

FormatException

The slice does not contain exactly one JSON value.

ReadRawValue()

Reads the next JSON value and returns its raw JSON text.

public string ReadRawValue()

Returns

string

The raw JSON representation of the next value.

Remarks

Uses the default depth limit of 64. Converters should use ReadRawValue(SerializationContext) to preserve the active operation's limits.

ReadRawValue(SerializationContext)

Reads the next JSON value and returns its raw JSON text using the active operation's limits.

public string ReadRawValue(SerializationContext context)

Parameters

context SerializationContext

The active serialization context.

Returns

string

The raw JSON representation of the next value.

ReadRequiredBase64Bytes()

Reads a required base64-encoded JSON string value.

public byte[] ReadRequiredBase64Bytes()

Returns

byte[]

The decoded bytes.

ReadRequiredString()

Reads a required JSON string value.

public string ReadRequiredString()

Returns

string

The decoded string value.

ReadSByte()

Reads a JSON number as a signed 8-bit integer.

public sbyte ReadSByte()

Returns

sbyte

The parsed value.

ReadSingle()

Reads a JSON number as a finite single-precision floating-point value.

public float ReadSingle()

Returns

float

The parsed value.

ReadStartArray()

Reads the opening token for a JSON array.

public void ReadStartArray()

ReadStartObject()

Reads the opening token for a JSON object.

public void ReadStartObject()

ReadString()

Reads a JSON string value that may be null.

public string? ReadString()

Returns

string

The decoded string value, or null when the next token is a JSON null literal.

ReadStringSequence()

Reads a nullable JSON string as decoded UTF-8 bytes, without quotes or JSON escapes.

public ReadOnlySequence<byte>? ReadStringSequence()

Returns

ReadOnlySequence<byte>?

Null for a null literal, a borrowed slice for unescaped sequence input, or GC-owned decoded storage.

Remarks

Escaped input is decoded, never returned as escaped text. Borrowed results must not outlive the input buffers.

ReadStringSpan()

Reads decoded UTF-8 string bytes, without surrounding quotes.

public ReadOnlySpan<byte> ReadStringSpan()

Returns

ReadOnlySpan<byte>

A borrowed span for contiguous unescaped input, otherwise a GC-owned token copy.

Exceptions

FormatException

The next token is not a non-null JSON string.

ReadUInt16()

Reads a JSON number as an unsigned 16-bit integer.

public ushort ReadUInt16()

Returns

ushort

The parsed value.

ReadUInt32()

Reads a JSON number as an unsigned 32-bit integer.

public uint ReadUInt32()

Returns

uint

The parsed value.

ReadUInt64()

Reads a JSON number as an unsigned 64-bit integer.

public ulong ReadUInt64()

Returns

ulong

The parsed value.

ReadValueSeparator()

Reads the separator between consecutive JSON values.

public void ReadValueSeparator()

Skip(SerializationContext)

Skips over the next JSON value.

public void Skip(SerializationContext context)

Parameters

context SerializationContext

The active serialization context, including the remaining depth and cancellation token.

Remarks

Each array or object, including an empty one, consumes one depth step. The caller's context is not modified, so siblings retain the same depth budget.

Exceptions

InvalidOperationException

The value exceeds the remaining depth limit.

OperationCanceledException

The operation has been canceled.

TryReadEndArray()

Attempts to read the closing token for a JSON array.

public bool TryReadEndArray()

Returns

bool

true if the array terminator was consumed; otherwise, false.

TryReadEndObject()

Attempts to read the closing token for a JSON object.

public bool TryReadEndObject()

Returns

bool

true if the object terminator was consumed; otherwise, false.

TryReadNull()

Attempts to read a JSON null literal.

public bool TryReadNull()

Returns

bool

true if a null literal was consumed; otherwise, false.

TryReadStringSpan(out ReadOnlySpan<byte>)

Attempts to read decoded UTF-8 string bytes without allocating.

public bool TryReadStringSpan(out ReadOnlySpan<byte> span)

Parameters

span ReadOnlySpan<byte>

Receives a borrowed view of the string's content, without quotes.

Returns

bool

Whether the next string's content is unescaped and contiguous. Null, escaped content, or content spanning segments returns false without advancing.

Remarks

A successful span borrows the reader's input lifetime. Invalid JSON throws rather than returning false.