Unable to deserialize object datatype to given type using JavaScriptSerializer

110 views Asked by At

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

ChildClass details

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.

1

There are 1 answers

2
MD Zand On

Using Newtonsoft and the TypeNameHandling you can do this:

using Newtonsoft.Json;

var obj = new ParentClass()
{
    Name = "Charles",
    Item = new ChildClass()
    {
        Location = "Chicago"
    },
    Dept = new Department()
    {
        DeptName = "IT"
    }
};
JsonSerializerSettings jsonSerializationSetting = new JsonSerializerSettings();
jsonSerializationSetting.TypeNameHandling = TypeNameHandling.Auto;
var json = JsonConvert.SerializeObject(obj, jsonSerializationSetting);
var finalRes =  JsonConvert.DeserializeObject<ParentClass>(json, jsonSerializationSetting);

If just using JavaScriptSerializer uou can use SimpleTypeResolver So your code could be like this:

JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());

 var json =  serializer.Serialize(obj);
 var finalRes = serializer.Deserialize<ParentClass>(json);