C# DataContractSerializer在反序列化后将所有类属性设置为null
我成功地序列化了对象列表。现在我需要再次反序列化它。我注意到它只反序列化列表。项目的属性都为空 例如: 序列化xml:C# DataContractSerializer在反序列化后将所有类属性设置为null,c#,deserialization,C#,Deserialization,我成功地序列化了对象列表。现在我需要再次反序列化它。我注意到它只反序列化列表。项目的属性都为空 例如: 序列化xml: <ArrayOfLevel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/"> <Level> <size>0</size> <dif
<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>
这将在控制台中记录null。我看不出问题出在哪里。代码在Unity中的C#中运行,这对我来说很适合您的xml(在它以您最初描述的方式失败之后):
作为对象定义。我们能看到任何允许我们重新编程的东西吗?什么是
级别
?和Level.title
?Level只是一个类,它有一个名为size的int,一个名为难度的int和一个名为title的字符串。谢谢!多亏了你的代码,我才发现我错过了顶部的[DataContract]
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;
}
using (var reader = XmlReader.Create(path))
{
List<Level> loaded = (List<Level>)serializer.ReadObject(reader, true);
System.Console.WriteLine(loaded.Single().title);
}
[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; }
}