I was trying something new to test the serialization of objects using markup interface.
I know in real world this will not be the proper scenario if I follow proper coding standards. But just for the curiosity to learn some work around to achieve the de-serialization of the generated object.
I have following interface and classes:
interface intA {}
class classa : intA
{
public int a { get; set; }
public int b { get; set; }
}
class classb : intA
{
public string c { get; set; }
public string d { get; set; }
public int e { get; set; }
}
class classsd
{
public List<intA> obj { get; set; }
}
I have written following serialization and de-serialization code as follows in main method using 'Newtonsoft.json'.
classsd objd = new classsd();
objd.obj = new List<intA>();
objd.obj.Add(new classa() { a = 1, b = 2 });
objd.obj.Add(new classb() { c = "asd", d = "qwe", e = 1 });
var a = JsonConvert.SerializeObject(objd);
string json = @"{'obj':[{'a':1,'b':2},{'c':'asd','d':'qwe','e':1}]}";
var temp = JsonConvert.DeserializeObject<classsd>(a);
I get proper serialization string, but when I try to de-serialize, an exception is thrown:
Newtonsoft.Json.JsonSerializationException: 'Could not create an instance of type ConsoleApp1.intA. Type is an interface or abstract class and cannot be instantiated.'...
Serialized string is as follows:
{'obj': [{'a': 1, 'b': 2}, {'c': 'asd', 'd': 'qwe', 'e': 1 }]}
Is there any workaround to achieve this kind of de-serialization?