序列化list对象

本文关键字:对象 list 序列化 | 更新日期: 2023-09-27 18:13:30

我有一个类型对象的泛型列表,我试图序列化它,但反序列化不会给我带来好的结果。下面是我要做的:

List<object> sample_list = new List<object>();
        sample_list.Add(new Sample() {  type=0,message="I am the first"});
        sample_list.Add(new Sample1() { type=1,message1 = "I am the 2" });
        sample_list.Add(new Sample2() { type=2,message2 = "I am the 3" });
       string serial= JsonConvert.SerializeObject(sample_list);
       List<object> list = JsonConvert.DeserializeObject<List<object>>(serial);
       lstbox.ItemsSource = list;
       foreach(var item in list)
       {
            if (item is Sample)
            {
                MessageBox.Show("Item is sample");
            }
       }

但是消息框没有显示。应该做些什么才能使它正确工作?

序列化list对象

您将list反序列化为object的列表,为什么您期望CLR将这些对象识别为SampleSample1 ?序列化JSON看起来:

[{"type":0,"message":"I am the first"},{"type":1,"message1":"I am the 2"},{"type":2,"message2":"I am the 3"}]

JSON。NET可以神奇地发现它们是Sample对象吗?做一个简单的测试,注意list[0].GetType().FullNameNewtonsoft.Json.Linq.JObject,而不是Sample

如果你想反序列化到Sample的列表,写:

var list = JsonConvert.DeserializeObject<List<Sample>>(serial);

,然后Json。. NET将尝试将每个属性从JSON匹配到Sample属性(但当然它有时不会成功,因为不是对象类型为Sample)。

如果你想序列化你的列表,你的JSON应该存储关于使用类型的信息,在JSON中有内置的选项。净:

string serial = JsonConvert.SerializeObject(sample_list,
    new JsonSerializerSettings { 
        TypeNameHandling = TypeNameHandling.Objects 
    });

序列化后的JSON如下:

[{"$type":"ConsolePusher.Sample, ConsolePusher","type":0,"message":"I am the first"}, 
 {"$type":"ConsolePusher.Sample1, ConsolePusher","type":1,"message1":"I am the 2"},
 {"$type":"ConsolePusher.Sample2, ConsolePusher","type":2,"message2":"I am the 3"}]

因此它将能够在反序列化时重新创建对象:

var list = JsonConvert.DeserializeObject<List<object>>(serial,
        new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Objects
        });

线索应该是json:

[{"type":0,"message":"I am the first"},
 {"type":1,"message1":"I am the 2"},
 {"type":2,"message2":"I am the 3"}]

您将其反序列化为List<object>。所以:有没有在json或API调用,给它一个提示,你想要一个Sample。如果您希望它存储类型名称并在反序列化期间使用它,则需要启用该选项:

var settings = new JsonSerializerSettings {
    TypeNameHandling = TypeNameHandling.Objects
};
string serial = JsonConvert.SerializeObject(sample_list, settings);
List<object> list =
    JsonConvert.DeserializeObject<List<object>>(serial, settings);

请注意,存储类型名称是脆弱的,并且是特定于实现的;它不是在所有情况下都能很好地工作。这里的json变成:

[{"$type":"Sample, ConsoleApplication43","type":0,"message":"I am the first"},
 {"$type":"Sample1, ConsoleApplication43","type":1,"message1":"I am the 2"},
 {"$type":"Sample2, ConsoleApplication43","type":2,"message2":"I am the 3"}]
相关文章: