Polymorphic type discriminator is not converted to enum during deserialization

558 Views Asked by At

I'm using enum field as type discriminator for polymorphic serialization/deserialization and faced strange behavior. A string value that is a type discriminator is not converted to enum and sets the default value of this enum.

Here's my C# model

[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(FixedPenalty), typeDiscriminator: "fixedPenalty")]
[JsonDerivedType(typeof(FixedRatePenalty), typeDiscriminator: "fixedRatePenalty")]
[JsonDerivedType(typeof(RelativePenalty), typeDiscriminator: "relativePenalty")]
public abstract class Penalty
{
    public PenaltyType Type { get; set; }
    public string Description { get; set; }

    public Penalty(PenaltyType type,
        string description)
    {
        Type = type;
        Description = description;
    }
}

Here's json that I send to the controller.

{
   "type": "relativePenalty",
   "description": "string",
   "rate": 10.9,
   "unit": "year"
}

As you can see the deserialization is working correctly, the object is of the correct type, however the enum is not being converted.

Debug

Is there any way to fix this behavior? Now I see two ways to solve the problem, either add a technical field purely for the discriminator to DTO model, which will duplicate "type" field, or check for the type casting and then convert to the desired model from a specific application layer, but I don't like these two ways.

0

There are 0 best solutions below