我有一个类型对象的通用列表,我正在尝试序列化它,但反序列化并没有取得好成绩。 这是我想要做的:
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");
}
}
但是消息框永远不会显示。 应该做些什么才能使其正常工作?
答案 0 :(得分:3)
您要将列表反序列化为object
列表,为什么您希望CLR将这些对象识别为Sample
或Sample1
?序列化的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().FullName
是Newtonsoft.Json.Linq.JObject
,而不是Sample
。
如果要反序列化为Sample
列表,请写:
var list = JsonConvert.DeserializeObject<List<Sample>>(serial);
然后Json.NET将尝试将每个属性从JSON匹配到Sample
属性(但当然它不会成功,因为对象的类型不是{{ 1}})。
如果要序列化列表,JSON应该存储有关已使用类型的信息,并且在JSON.NET中有内置选项:
Sample
然后序列化JSON看起来:
string serial = JsonConvert.SerializeObject(sample_list,
new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Objects
});
因此,它可以在反序列化时重新创建对象:
[{"$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"}]
答案 1 :(得分:2)
这里的线索应该是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调用中有 nothing ,它给出了一个你需要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"}]