I have classes as below
public class ParentClass
{
public string Name { get; set; }
public object Item { get; set; } = new object();
public Department Dept { get; set; }
}
public class ChildClass
{
public string Location { get; set; }
}
public class Department
{
public string DeptName { get; set; }
}
I'm trying to pass data and deserialize as below
var obj = new ParentClass()
{
Name = "Charles",
Item = new ChildClass()
{
Location = "Chicago"
},
Dept = new Department()
{
DeptName = "IT"
}
};
var json = new JavaScriptSerializer().Serialize(obj);
var finalRes = new JavaScriptSerializer().Deserialize<ParentClass>(json);
I'm assigning ChildClass to Item property which has datatype object. While debugging I'm able to see ChildClass details as below
When I serialize it, I have data as below Serialized data
and when it is deserialized, it has data as below Deserialized data
In Deserialized data , getting Item property details as Dictionary values instead of ChildClass type.
How to avoid object datatype getting converted to Dictionary while deserializing.
I want to assign given type ChildClass to object property Item even after deserializing aswell.
Using Newtonsoft and the TypeNameHandling you can do this:
If just using JavaScriptSerializer uou can use SimpleTypeResolver So your code could be like this: