У меня есть Enum, определяющий тип JSON:
Код: Выделить всё
public enum BlockType
{
T1,
T2
}
Код: Выделить всё
public class Container
{
required public List ListOfItems { get; set; }
}
[JsonPolymorphic(TypeDiscriminatorPropertyName = nameof(Type))]
[JsonDerivedType(typeof(Type1), 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; }
}
Код: Выделить всё
var jsonBody = """
{
"ListOfItems": [
{
"type": "T1",
"Value1": 10
},
{
"type": "T2",
"Value2": 11
}
]
}
""";
Код: Выделить всё
var deserializeOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
WriteIndented = true,
};
var decoded = JsonSerializer.Deserialize(jsonBody, deserializeOptions);
Код: Выделить всё
foreach (BaseType o in decoded.ListOfItems)
{
if (o.Type == BlockType.T1)
{
Type1 obj = (Type1)o;
}
}
Есть ли решение этой проблемы?
Подробнее здесь: https://stackoverflow.com/questions/783 ... nt-working