我成功序列化了一个对象列表。现在我需要再次反序列化它。我注意到它只反序列化列表。这些项的属性都是null。
示例:
序列化xml:
<ArrayOfLevel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/">
<Level>
<size>0</size>
<difficulty>1</difficulty>
<title>OverTheHill</title>
</Level>
</ArrayOfLevel>
反序列化:
FileStream stream = new FileStream(Path.Combine(Application.dataPath, "test.xml"), FileMode.Open);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
DataContractSerializer serializer = new DataContractSerializer(typeof(List<Level>));
List<Level> loaded = (List<Level>)serializer.ReadObject(reader, true);
reader.Close();
stream.Close();
foreach (Level level in loaded)
{
Debug.Log(level.title);
}
等级
public class Level
{
public int size;
public int difficulty;
public string title;
}
这在控制台中记录为null。我看不出问题出在哪里。代码在Unity中以C#
运行答案 0 :(得分:1)
对于我的xml(在你最初描述的方式失败后),这对我来说很好用:
using (var reader = XmlReader.Create(path))
{
List<Level> loaded = (List<Level>)serializer.ReadObject(reader, true);
System.Console.WriteLine(loaded.Single().title);
}
我建议您丢失XmlDictionaryReader
/ XmlDictionaryReaderQuotas
请注意我正在使用:
[DataContract]
public class Level
{
[DataMember(Order = 0)]
public int size { get; set; }
[DataMember(Order = 1)]
public int difficulty { get; set; }
[DataMember(Order = 2)]
public string title { get; set; }
}
作为对象定义。