Repository navigation
Closed
Labels
Description
Description
When using JsonSerializer to perform polymorphic deserialization, an exception will be thrown if the type discriminator property is required.
Reproduction Steps
using System.Text.Json;
using System.Text.Json.Serialization;
const string json = """
{ "type": "derived" }
""";
try
{
var data = JsonSerializer.Deserialize(json, DataSerializerContext.Default.Base);
Console.WriteLine(data);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(Derived), "derived")]
abstract class Base
{
[JsonRequired]
public DataType Type { get; init; }
}
sealed class Derived : Base
{
}
enum DataType
{
Derived
}
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
[JsonSerializable(typeof(Base))]
[JsonSerializable(typeof(Derived))]
sealed partial class DataSerializerContext : JsonSerializerContext;Expected behavior
Can be deserialized successfully.
Actual behavior
An exception has occurred.
System.Text.Json.JsonException: JSON deserialization for type 'Derived' was missing required properties including: 'type'.
at System.Text.Json.ThrowHelper.ThrowJsonException_JsonRequiredPropertyMissing(JsonTypeInfo parent, BitArray requiredPropertiesSet)
at System.Text.Json.Serialization.Converters.ObjectWithParameterizedConstructorConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter`1.OnTryReadAsObject(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, Object& value)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value, Boolean& isPopulatedValue)
at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, T& value, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.Deserialize(Utf8JsonReader& reader, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo`1 jsonTypeInfo, Nullable`1 actualByteCount)
at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo`1 jsonTypeInfo)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonTypeInfo`1 jsonTypeInfo)
at Program.<Main>$(String[] args) in D:\Source\Repos\ConsoleApp1\ConsoleApp1\Program.cs:line 10
Regression?
No response
Known Workarounds
Deserialization will be successful if changed as follows.
Specify a concrete type.
var data = JsonSerializer.Deserialize(json, DataSerializerContext.Default.Derived);Or, remove the [JsonRequired] attribute from Type.
// [JsonRequired]
public DataType Type { get; init; }There is also the following method for determining the actual type in code.
[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(Derived), "derived")]
abstract class Base
{
[JsonIgnore]
public abstract DataType Type { get; }
}
sealed class Derived : Base
{
public override DataType Type => DataType.Derived;
}Or
[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(Derived), "derived")]
abstract class Base
{
// remove Type
}
sealed class Derived : Base
{
}
if (data is Derived d) { ... }Configuration
.NET 9.0
Windows 11 24H2
x64
Other information
No response
Activity
dotnet-policy-service commentedon Nov 28, 2024
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis
See info in area-owners.md if you want to be subscribed.
pinkfloydx33 commentedon Nov 28, 2024
I'm pretty sure that treating the discriminator as a proper property is still not a supported scenario, meaning you can't customize it (which is what JsonRequired would do). Though I might be wrong.
#79933 (comment)
I believe it's treated as a metadata property. You end up with a real property (on your class) and a metadata property with the same name, the latter taking priority. I think it used to be the case that it wouldn't even deserialize into the object (see my comment in link, we had to come up with all sorts of workarounds)
aetos382 commentedon Nov 29, 2024
It is true that the type discriminator property should be read-only. But that can be achieved by making the property get-only or init-only, which is a separate issue from the deserializer not supporting it.
However, if I want to identify the type, I can do it like this, so the importance of this problem is not high.
OR
I've also added a workaround to the original post.
eiriktsarpalis commentedon Nov 29, 2024
Essentially a duplicate of #72170. Reusing type discriminator property names for object properties isn't supported, yet the STJ doesn't validate for this. What you're observing is undefined behaviour because this validation is not taking place.