Код: Выделить всё
[JsonPolymorphic]
[JsonDerivedType(typeof(DerivedClass), "derived")]
public abstract class BaseClass
{
public BaseClass() { }
}
public class DerivedClass : BaseClass
{
public string? Whatever { get; set; }
}
Код: Выделить всё
$type
Код: Выделить всё
var jsonWorks = "{\"$type\": \"derived\", \"whatever\": \"Bar\"}";
var jsonBreaks = "{\"whatever\": \"Bar\", \"$type\": \"derived\"}";
var obj1 = JsonSerializer.Deserialize(jsonWorks);
var obj2 = JsonSerializer.Deserialize(jsonBreaks); // This one will throw an exception
Код: Выделить всё
System.NotSupportedException: 'Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'MyApp.BaseClass'. Path: $ | LineNumber: 0 | BytePositionInLine: 12.'
Код: Выделить всё
NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'MyApp.BaseClass'.
Подробнее здесь: https://stackoverflow.com/questions/776 ... ot-the-fir