Skip to content

SingleOrArrayConverter<T> Class

Reads and writes a JSON value that may be either a single element of T or an array of such elements, exposing it uniformly to .NET as T[]. On write, a single-element array is emitted as a bare scalar (not an array), matching the OAuth 2.0 / OpenID Connect convention used for parameters such as aud and response_type.

C#
public class SingleOrArrayConverter<T> : System.Text.Json.Serialization.JsonConverter<T[]>

Type parameters

T

The element type. A converter for T must be available in the serializer options.

Inheritance System.ObjectSystem.Text.Json.Serialization.JsonConverterSystem.Text.Json.Serialization.JsonConverter<T[]> → SingleOrArrayConverter<T>

Methods

SingleOrArrayConverter<T>.Read(Utf8JsonReader, Type, JsonSerializerOptions) Method

Reads and converts the JSON to a string array. If the JSON token is a single string, it returns an array containing one element. If it is an array of strings, it converts each element and returns them in an array.

C#
public override T[]? Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options);

Parameters

reader System.Text.Json.Utf8JsonReader

The reader from which to read the JSON document.

typeToConvert System.Type

The type to convert. Expected to be a string array.

options System.Text.Json.JsonSerializerOptions

Options for the serializer.

Returns

T[]
An array of strings parsed from the JSON input.

Exceptions

System.Text.Json.JsonException
Thrown if an unexpected token type is encountered.

SingleOrArrayConverter<T>.Write(Utf8JsonWriter, T[], JsonSerializerOptions) Method

Writes a string array to a JSON writer. If the array contains a single string, it writes it as a single string value. If it contains multiple strings, it writes them as an array of strings.

C#
public override void Write(System.Text.Json.Utf8JsonWriter writer, T[]? value, System.Text.Json.JsonSerializerOptions options);

Parameters

writer System.Text.Json.Utf8JsonWriter

The writer to which the JSON will be written.

value T[]

The string array to write.

options System.Text.Json.JsonSerializerOptions

Options for the serializer.

Exceptions

System.ArgumentNullException
Thrown if the writer or value is null.