Skip to content

Add ReadOnlySpan<char> overloads to JsonSerializer.Deserialize #1235

@ahsonkhan

Description

@ahsonkhan

We already have string-based overloads along with UTF-8 byte span overloads. We should add ReadOnlySpan<char> based overloads too to avoid forcing folks who already have string span slices to unnecessary call ToString().

On such use case is in https://stackoverflow.com/questions/58845880/how-to-deserialize-readonlyspanchar-to-object-using-system-text-json

Add:

public static partial class JsonSerializer
{
    public static object? Deserialize(ReadOnlySpan<char> json, Type returnType, JsonSerializerOptions? options = null);
    [return: MaybeNull]
    public static TValue Deserialize<TValue>(ReadOnlySpan<char> json, JsonSerializerOptions? options = null);
}

Existing:

public static partial class JsonSerializer
{
    public static object? Deserialize(ReadOnlySpan<byte> utf8Json, Type returnType, JsonSerializerOptions? options = null);
    public static object? Deserialize(string json, Type returnType, JsonSerializerOptions? options = null);
    public static object? Deserialize(ref Utf8JsonReader reader, Type returnType, JsonSerializerOptions? options = null);
    public static ValueTask<object?> DeserializeAsync(Stream utf8Json, Type returnType, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default);
    public static ValueTask<TValue> DeserializeAsync<TValue>(Stream utf8Json, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default);
    [return: MaybeNull]
    public static TValue Deserialize<TValue>(ReadOnlySpan<byte> utf8Json, JsonSerializerOptions? options = null);
    [return: MaybeNull]
    public static TValue Deserialize<TValue>(string json, JsonSerializerOptions? options = null);
    [return: MaybeNull]
    public static TValue Deserialize<TValue>(ref Utf8JsonReader reader, JsonSerializerOptions? options = null);
}

It is arguable that the string overload was mainly added for usability and folks who care about performance should really be using the UTF-8 overloads instead of us adding ReadOnlySpan<char> overloads (essentially, wherever they got the string/UTF-16 span from, they should replace try to get the UTF-8 bytes or stream instead). For example, instead of doing File.ReadAllText, pass in the FileStream directly.

However, we have added such overloads to APIs that accept string elsewhere, and there is still value for scenarios where the input JSON cannot be changed to something other than string.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions