Skip to content

TryDeserialize ​

Deserializes a JSON string into T without throwing on invalid input, for a request body, queue message, or user-supplied file where malformed JSON is an expected outcome.

Returns false for a malformed payload and for the JSON literal null, so a true result always yields something usable; any other failure still throws, so a genuine programming error is not swallowed. result comes first because an out parameter cannot follow an optional one, and there is no stream equivalent because out is not allowed on async methods, so a stream uses DeserializeAsync.

Usage ​

csharp
using AlmightyShogun.Utils;

if (!payload.TryDeserialize(out Order? order))
{
    logger.LogWarning("Discarded a message that was not valid JSON.");

    return;
}

await ProcessAsync(order);
csharp
using System.Text.Json;
using AlmightyShogun.Utils;

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

bool parsed = payload.TryDeserialize(out Order? order, options);
csharp
public sealed record Order(int OrderId, string CustomerName);

Parameters

result: out T?
When the method returns true, contains the deserialized value, annotated so the compiler treats it as non-null from that point. Left at the default for T otherwise.

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

Returns

true when a non-null value was read; otherwise false.

Type signature ​

csharp
public bool TryDeserialize<T>(
    [NotNullWhen(true)] out T? result,
    JsonSerializerOptions? options = null
);

All packages are released under the MIT License.