Skip to content

System.text.json serializes virtual property decorated with JsonPropertyName attribute twice. #92780

@alexaloni

Description

@alexaloni

Description

System.text.json serializes property decorated with JsonPropertyName attribute in the base class is recording 2 records in the output json , one with property name as key and a second with name specified in the attribute.

Reproduction Steps

Console.WriteLine(JsonSerializer.Serialize(new Derived()));

public class Base
{
    [JsonPropertyName("test")]
    public virtual string Id { get => "base"; set { } }
}

public class Derived : Base
{
    public override string Id { get => "derived"; set { } }
}

Expected behavior

only single entry with name specified in the JsonPropertyName should be adde to json.

Actual behavior

{"Id":"derived","test":"derived"} -> added twice with different names.

Regression?

We have seen this since the initial version.

Known Workarounds

I see two possible workarounds:

  1. Try using the base type as the generic parameter when creating your container object. Unlike Json.NET, STJ is sensitive when it comes to what type is being declared statically at the serialization callsite, or
  2. Replicate the JsonPropertyName property in the overrides. It's more boilerplate, but at least it's the best way to get the desired behavior while we ship a fix.

Configuration

.NET 7

Other information

No response

Metadata

Metadata

Labels

area-System.Text.Jsonbugin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions