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);
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 of
Person p2 = (Person)dic["data"];
And
person.age
will be25
.EDIT:
Hope Helps!