dotnet / dotnet/runtime

Property name conflicts with discriminator even when property is [JsonIgnore]

Open
#123,431 3 comments 0 reactions 0 assignees View on GitHub
area-System.Text.Json bug
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Description

When polymorphism is being used, if the type discriminator and a property on the C# type have the same name, even if that property is [JsonIgnore], deserialization fails.

### Reproduction Steps

```csharp
using System.Text.Json;
using System.Text.Json.Serialization;

Console.WriteLine(JsonSerializer.Deserialize(
"""{"type":"derived"}""",
JsonSerializerOptions.Web));

[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(Derived), "derived")]
abstract class Base
{
[JsonPropertyName("type")]
[JsonIgnore]
public abstract string Type { get; }
}

class Derived : Base
{
public override string Type => "derived";
}
```

### Expected behavior

Succeeds

### Actual behavior

```
Unhandled exception. System.InvalidOperationException: The type 'Derived' contains property 'type' that conflicts with an existing metadata property name. Consider either renaming it or ignoring it with JsonIgnoreAttribute.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_PropertyConflictsWithMetadataPropertyName(Type type, String propertyName)
at System.Text.Json.Serialization.Metadata.PolymorphicTypeResolver..ctor(JsonSerializerOptions options, JsonPolymorphismOptions polymorphismOptions, Type baseType, Boolean converterCanHaveMetadata)
at System.Text.Json.Serialization.Metadata.JsonTypeInfo.Configure()
at System.Text.Json.Serialization.Metadata.JsonTypeInfo.g__ConfigureSynchronized|174_0()
at System.Text.Json.JsonSerializerOptions.GetTypeInfoInternal(Type type, Boolean ensureConfigured, Nullable`1 ensureNotNull, Boolean resolveIfMutable, Boolean fallBackToNearestAncestorType)
at System.Text.Json.JsonSerializerOptions.GetTypeInfoForRootType(Type type, Boolean fallBackToNearestAncestorType)
at System.Text.Json.JsonSerializer.GetTypeInfo[T](JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
at Program.$(String[] args)
```

### Regression?

No

### Known Workarounds

No workarounds known, other than choosing a different C# property name.

### Configuration

.NET 10

### Other information

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.