Skip to content

System.Text.Json inconsistent behavior using JsonExtensionData on JsonObject #61080

@WeihanLi

Description

@WeihanLi

Description

When I use the JsonExtensionData, I found that the JsonObject is a little different from Dictionary<string, object>/Dictionary<string, JsonElement>, not sure if it‘s by design or a bug.

image

The last one is using the JsonObject, test code is below

Reproduction Steps

using static System.Console;

var p = JsonSerializer.Deserialize<Person>(jsonString);
ArgumentNullException.ThrowIfNull(p, nameof(p));
WriteLine(JsonSerializer.Serialize(p));

var p1 = JsonSerializer.Deserialize<Person1>(jsonString);
ArgumentNullException.ThrowIfNull(p1, nameof(p1));
WriteLine(JsonSerializer.Serialize(p1));

var p2 = JsonSerializer.Deserialize<Person2>(jsonString);
ArgumentNullException.ThrowIfNull(p2, nameof(p2));
WriteLine(JsonSerializer.Serialize(p2));

var p3 = JsonSerializer.Deserialize<Person3>(jsonString);
ArgumentNullException.ThrowIfNull(p3, nameof(p3));
WriteLine(JsonSerializer.Serialize(p3));


    public record Person(string Name, int Age);

    public record Person1(string Name, int Age) : Person(Name, Age)
    {
        [JsonExtensionData]
        public Dictionary<string, object?> Extensions { get; set; } = new();
    }

    public record Person2(string Name, int Age) : Person(Name, Age)
    {
        [JsonExtensionData]
        public Dictionary<string, JsonElement> Extensions { get; set; } = new(StringComparer.OrdinalIgnoreCase);
    }

    public record Person3(string Name, int Age) : Person(Name, Age)
    {
        [JsonExtensionData]
        public JsonObject? Extensions { get; set; }
    }

Expected behavior

Maybe the JsonObject should behave as Dictionary<string, object>/Dictionary<string, JsonElement>

Actual behavior

image

Regression?

No response

Known Workarounds

No response

Configuration

.NET 6 RC2
Windows
x64

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions