Mycom
Mycom

Reputation: 39

DataContractSerializer sets all class attributes to null after deserialization

i successfully serialized a List of objects. Now i need to deserialize it again. I noticed that it only deserialize the list. The attributes of the items are all null.

Example:

serialized 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>

deserialization:

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);
}

Level class

public class Level
{
    public int size;
    public int difficulty;
    public string title;
}

This logs null in the console. I can't see where the problem is. The code runs inside Unity in C#

Upvotes: 0

Views: 239

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062800

This works fine for me with your xml (after it failed in the way you described originally):

using (var reader = XmlReader.Create(path))
{
    List<Level> loaded = (List<Level>)serializer.ReadObject(reader, true);
    System.Console.WriteLine(loaded.Single().title);
}

I suggest simply losing the XmlDictionaryReader / XmlDictionaryReaderQuotas

Note that I'm using:

[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; }
}

as the object definition.

Upvotes: 1

Related Questions