0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Yogesh Jadhav
  • 127
  • 2
  • 2
  • 7
  • Any reason you can't make a class that contains those five properties and use that? – JBC Aug 14 '17 at 13:51
  • You need to tell Json.Net to include the type in the serialization, i.e.: new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }. Otherwise, how would it know which type to deserialize into? You pass these settings as an argument to both SerializeObject and DeSerializeObject if I recall correctly. – kkirk Aug 14 '17 at 13:58
  • Please read [ask] and share your research. Plenty of existing questions already handle this very subject. – CodeCaster Aug 14 '17 at 14:00

0 Answers0