【发布时间】:2021-08-15 19:55:33
【问题描述】:
我有以下测试类
public class Test
{
public int MyProperty { get; set; }
public ArrayList list { get; set; }
}
public class Employee
{
public int MyProperty { get; set; }
public string Name { get; set; }
}
以及下面的代码
static void Main(string[] args)
{
Employee e1 = new Employee();
e1.MyProperty = 1;
e1.Name = "Yash";
Employee e2 = new Employee();
e2.MyProperty = 1;
e2.Name = "Yash";
Test t = new Test();
t.list = new ArrayList();
t.list.Add(e1);
t.list.Add(e2);
string text = JsonSerializer.Serialize(t);
Test t2 = new Test();
t2 = JsonSerializer.Deserialize<Test>(text);
}
当我使用 Newtonsoft 反序列化时,我在数组 List 中看到 JObjects 而不是 Employee 对象。我可以通过创建 ArrayList 转换器使用 Newtonsoft.Json 解决这个问题。
但是,System.text.Json 无法做到这一点。如何使用 System.Text.Json 反序列化此 ArrayList?这是我需要支持的古老代码,每次我反序列化一个 ArrayList 时,我都知道它应该包含哪种对象类型。
【问题讨论】:
-
我的建议:不要使用
ArrayList。如果您需要事物列表,则使用事物列表,例如List<Employee> -
@DavidG 是的,如果我们要开始一些新的东西,那是最好的方法,但我可以接受我目前所拥有的。不幸的是,由于项目中的各种原因,我无法更改为 List
。 -
如果您可以将
list属性转换为泛型而不是ArrayList,那将是理想的。如果没有,您可以在 System.Text.Json 中创建自定义序列化程序。见stackoverflow.com/questions/67622527/… -
@JackA。 Employee 只是这里的一个例子,但我有很多这样的场景,上面的例子是针对
DateTimeOffset对象的,所以如果我想为Manager、Employee、Admin等对象写这个,我需要创建多个转换器?我能不能创建一个通用转换器,就像我们在这里所做的那样使用 Newtonsoft.Json stackoverflow.com/questions/41564842/… -
您的自定义转换器将基于
JsonConverter<ArrayList>,因此您可以在内部检查项目类型。
标签: c# .net-core serialization deserialization system.text.json