Assume the below model:
public enum TypeAModels
{
A = 1,
B = 2
}
public abstract class TypeA
{
public abstract TypeAModels TypeAModels { get; }
}
public class TypeA_A : TypeA
{
public int Age { get; set; }
public TypeB TypeB { get; set; }
public override TypeAModels TypeAModels => TypeAModels.A;
}
public class TypeA_B : TypeA
{
public string Name { get; set; }
public override TypeAModels TypeAModels => TypeAModels.B;
}
public enum TypeBModels
{
A = 1,
B = 2
}
public abstract class TypeB
{
public abstract TypeBModels TypeBModels { get; }
}
public class TypeB_A : TypeB
{
public int Year { get; set; }
public override TypeBModels TypeBModels => TypeBModels.A;
}
public class TypeB_B : TypeB
{
public string UserName { get; set; }
public override TypeBModels TypeBModels => TypeBModels.B;
}
I’d like to Serialize/deserialize the typeAA
object, like this:
var typeAA = new TypeA_A() { Age = 30, TypeB = new TypeB_A { Year = 1982 } };
var jsonString = JsonSerializer.Serialize(typeAA, new JsonSerializerOptions());
var deserializedTypeAA = JsonSerializer.Deserialize<TypeA_A>(jsonString, new JsonSerializerOptions());
Currently, when I run the above code I get the 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 'TypeB'.
I understand that I have a problem with the TypeA_A
nested field TypeB
, but I can’t find a way how to deserialize such an object that needs a converter itself as TypeA
but also needs another convertor for its internal field TypeB
.
The only way I can think of is to read manually each field separately.
Is there a more elegant way?