Skip to content

DeserializeAsync ​

Deserializes a readable stream into T without buffering it into a string first, for file and network streams. Use TryDeserialize when the JSON is already in memory.

The stream is read from its current position and is not disposed, and a malformed payload throws JsonException, which must be caught at the call site because out parameters are not allowed on async methods.

Usage ​

csharp
using AlmightyShogun.Utils;

await using FileStream stream = File.OpenRead("orders.json");

Order[]? orders = await stream.DeserializeAsync<Order[]>(
    cancellationToken: cancellationToken
);
csharp
using System.Text.Json;
using AlmightyShogun.Utils;

JsonSerializerOptions options = new()
{
    PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
};

Order[]? orders = await stream.DeserializeAsync<Order[]>(options);
csharp
public sealed record Order(int OrderId, string CustomerName);

Parameters

options: JsonSerializerOptions?
Serializer options to apply. Left unset, the package defaults are used, which bind an ASP.NET Core payload on the same rules the API serialized it with, meaning camel-case naming, case-insensitive property matching, and numbers accepted from JSON strings.
Default: null

cancellationToken: CancellationToken
Stops the read part way through. The stream is left at wherever reading reached, so a cancelled call leaves it unusable for a second attempt unless the caller can rewind it.
Default: default

Returns

A task containing the deserialized value, or null when the JSON payload resolves to null.

Type signature ​

csharp
public Task<T?> DeserializeAsync<T>(
    JsonSerializerOptions? options = null,
    CancellationToken cancellationToken = default
);

All packages are released under the MIT License.