How to typecasting the object class from the dictionary value (object)

150 Views Asked by At

How can I fix the typecast error...
I want to create new my object using by 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);
1

There are 1 best solutions below

5
On

You getting dictionary of string,Person and casting to Person, thats why it is throwing an exception.

Try var person = JsonConvert.DeserializeObject<Person>((dic["data"].ToString()));

instead ofPerson p2 = (Person)dic["data"];

And person.age will be 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!