c# - How to typecasting the object class from the dictionary value (object) -


how can fix typecast error...
want create new object using json..

i attached example code..

 public class person  {      public int age;      public person(int _age)      {          this.age = _age;      }  }   dictionary<string, object> dic = new dictionary<string, object>();  dic.add("type", "person");  dic.add("data", new person(25));   string json = jsonconvert.serializeobject(dic);   dic = jsonconvert.deserializeobject<dictionary<string, object>>(json);   person p2 = (person)dic["data"];  console.writeline(p2); 

you getting dictionary of string,person , casting person, thats why throwing exception.

try var person = jsonconvert.deserializeobject<person>((dic["data"].tostring()));

instead ofperson p2 = (person)dic["data"];

and person.age 25.

edit:

  public mainwindow()         {             initializecomponent();              dictionary<string, object> dic = new dictionary<string, object>();             dic.add("type", "person");             dic.add("data", new person(25));              string json = jsonconvert.serializeobject(dic);              dic = jsonconvert.deserializeobject<dictionary<string, object>>(json);             var person = jsonconvert.deserializeobject<person>((dic["data"].tostring()));              console.writeline(person.age);         } 

hope helps!


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -