I deserialized json string to List<ClassB>
and now I want to cast it to List<ClassA>
before I return it from
BindModel
method. I need casting because the methods expects to get List<ClassA>
.
Why I get error while casting? After all, ClassB
inherits from ClassA
. What should I do?
P.S. this question is extended from this post. In line new DataContractJsonSerializer(typeof(List<ClassB>));
instead of List<ClassB>
the type will be constructed at runtime.
public override object BindModel(...)
{
var serializer = new DataContractJsonSerializer(typeof(List<ClassB>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("[{\"id\":\"1\",\"name\":\"name\"}]"));
var list = serializer.ReadObject(ms);
return (List<ClassA>)list;
}
[KnownType(typeof(ClassA))]
[DataContract]
public class ClassA
{
public ClassA();
}
[KnownType(typeof(ClassB))]
[DataContract]
public class ClassB : ClassA
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "name")]
public string CategoryName { get; set; }
}