.NET 8..0 System.Text.JSON Deserialize Json Polymorphic isn’t working

  Kiến thức lập trình

I’m having trouble de-serializing Json Polymorhpically. Here is a minimal example:

I have an Enum defining the type of JSON:

public enum BlockType 
{
    T1,
    T2
}

The base class and the child class (and the container):

public class Container
{
    required public List<BaseType> ListOfItems { get; set; }
}

[JsonPolymorphic(TypeDiscriminatorPropertyName = nameof(Type))]
[JsonDerivedType(typeof(Type2), nameof(BlockType.T1))]
[JsonDerivedType(typeof(Type2), nameof(BlockType.T2))]
public class BaseType
{
    [JsonConverter(typeof(JsonStringEnumConverter))]
    required public BlockType Type { get; set; }
}

public class Type1 : BaseType
{
    required public int Value1 { get; set; }
}

public class Type2 : BaseType
{
    required public int Value2 { get; set; }
}

I have a input JSON:

var jsonBody = """
{
  "ListOfItems": [
    {
      "type": "T1",
      "Value1": 10
    },
    {
      "type": "T2",
      "Value2": 11
    }
  ]
}
""";

And call the serializer:

var deserializeOptions = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    WriteIndented = true,
};
var decoded = JsonSerializer.Deserialize<Container>(jsonBody, deserializeOptions);

The serializer does NOT returns any errors what so ever. However, when I checked the returned type and the list, Container.ListOfItems, every items in it is the BaseType, instead of the derived Type1 or Type2. In fact, if I cast the object:

foreach (BaseType o in decoded.ListOfItems)
{
    if (o.Type == BlockType.T1)
    {
        Type1 obj = (Type1)o;
    }
}

I would instead get an InvalidCastException: Cannot convert BaseType to Type1.

Is there a solution to this problem?

LEAVE A COMMENT