Skip to content

For polymorphic deserialization, the type discriminator property cannot be set to required. #110248

Closed

Description

@aetos382

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

  1. added
    untriaged
    on Nov 28, 2024
  2. dotnet-policy-service commented on Nov 28, 2024

    @dotnet-policy-service
    Contributor

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

  3. pinkfloydx33 commented on Nov 28, 2024

    @pinkfloydx33

    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)

  4. aetos382 commented on Nov 29, 2024

    @aetos382
    Author

    The fact it has a setter implies you can change the underlying type by changing the value, which wouldn't make sense.
    (from #79933 (comment))

    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.

    [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) { ... }

    I've also added a workaround to the original post.

  5. eiriktsarpalis commented on Nov 29, 2024

    @eiriktsarpalis
    Member

    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.

  6. removed
    untriaged
    on Nov 29, 2024
  7. locked and limited conversation to collaborators on Dec 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions