Hello,
I'm trying to deserialize a JSon file to an instance of a class that contains an abstract list. Serializing the instance to the Json works well (check the json file below). When deserializing I get a "System.MemberAccessException" with the message "Cannot create an abstract class". Obvisouly the deseralizer is trying to instantiate the abstract class and not the concrete class.
In my example the deserialized class is called ElementContainer :
namespace Data
{
[DataContract]
[KnownType(typeof(ElementA))]
[KnownType(typeof(ElementB))]
public class ElementContainer
{
[DataMember]
public List<Element> Elements { get; set; }
}
[DataContract]
public abstract class Element
{
}
[DataContract]
public class ElementA : Element
{
[DataMember]
int Id { get; set; }
}
[DataContract]
public class ElementB : Element
{
[DataMember]
string Name { get; set; }
}
}
This is the Json file that was serialized and that I'm trying to deserialize. Notice the "__type" field for the deserializer to create the concrete classes :
{
"Elements":
[
{
"__type":"ElementA:#Data",
"Id":1
},
{
"__type":"ElementB:#Data",
"Name":"MyName"
}
]
}
The following is the code I'm using for deserialization :
public T LoadFromJSON<T>(string filePath)
{
try
{
using (FileStream stream = File.OpenRead(filePath))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T contract = (T)serializer.ReadObject(stream);
return contract;
}
}
catch (System.Exception ex)
{
logger.Error("Cannot deserialize json " + filePath, ex);
throw;
}
}
It is possible to make the deserialization work ?
Thanks !