Skip to content

Async and sync boxed serialize differ in behaviour (System.Text.Json) #31464

@Mpdreamz

Description

@Mpdreamz
private static JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions { WriteIndented = false };

static async Task<int> Main(string[] args)
{
    var empty = new {};
    var valued = new {x = 1, y = true};

    Console.WriteLine("Generic");
    await Write(empty);
    await Write(valued);
    Console.WriteLine("Boxed");
    await BoxedWrite(empty);
    await BoxedWrite(valued);

    return 0;
}

private static async Task Write<T>(T x)
{
    var blocking = Serialize(x);
    var async = await SerializeAsync(x);

    Console.WriteLine("-- blocking --");
    Console.WriteLine(blocking);
    Console.WriteLine("-- async --");
    Console.WriteLine(async);
}
private static async Task BoxedWrite(object x)
{
    var blocking = Serialize(x);
    var async = await SerializeAsync(x);

    Console.WriteLine("-- blocking --");
    Console.WriteLine(blocking);
    Console.WriteLine("-- async --");
    Console.WriteLine(async);
}

private static string Serialize<T>(T data)
{
    using var stream = new MemoryStream();
    using var writer = new Utf8JsonWriter(stream);
    JsonSerializer.Serialize<T>(writer, data, _jsonSerializerOptions);
    return Encoding.UTF8.GetString(stream.ToArray());

}
private static async Task<string> SerializeAsync<T>(T data)
{
    using var stream = new MemoryStream();
    await JsonSerializer.SerializeAsync<T>(stream, data, _jsonSerializerOptions, default);
    return Encoding.UTF8.GetString(stream.ToArray());
}

emits:

Generic
-- blocking --
{}
-- async --
{}
-- blocking --
{"x":1,"y":true}
-- async --
{"x":1,"y":true}
Boxed
-- blocking --
{}
-- async --
{}
-- blocking --
{"x":1,"y":true}
-- async --
{}
            int maxPropertyIndex = JsonClassInfo.PropertyCacheArray.Length;

Is always 0 in the NextProperty() for WriteStackFrame in the case of an async serialize on a boxed value.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions