asp.net 无法使用JavaScriptSerializer将对象数据类型反序列化为给定类型

ddrv8njm  于 2022-12-01  发布在  .NET
关注(0)|答案(1)|浏览(153)

我的课程如下

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; }

    }

我尝试传递数据并反序列化,如下所示

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);

我将ChildClass赋给Item属性,该属性的数据类型为object
ChildClass details
当我序列化它的时候,我有如下的数据Serialized data
反序列化时数据如下Deserialized data
在反序列化的数据中,获取Item属性详细信息作为Dictionary值,而不是ChildClass类型。
如何避免在反序列化时将object数据类型转换为Dictionary
我想将给定类型ChildClass分配给object属性Item,即使在反序列化之后也是如此

mm9b1k5b

mm9b1k5b1#

使用Newtonsoft和TypeNameHandling可以执行以下操作:

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);

如果仅仅使用JavaScriptSerializer uou就可以使用SimpleTypeResolver那么你的代码可能是这样的:

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

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

相关问题