StuffHappens
StuffHappens

Reputation: 6557

XML Serialization - what is wrong? C#


I've got the following classes:

               public class ObjectCollection :  List<ObjectRow>
                {

                    public Dictionary<int, ObjectRow> ObjectsAutomat { get; private set; }
                    public Dictionary<int, ObjectRow> ObjectsDelayed  { get; private set; }
                    public Dictionary<int, ObjectRow> ObjectsHandle { get; private set; }
                    public Dictionary<int, ObjectRow> ObjectsNew { get; private set; }

                    public Dictionary<string, string> Fields
                    { get; protected set; }

                    public string AddressParserFieldName { get; set; }
        // Some methods here

                }

      public class ObjectRow
        {
            public int ID { get; set; }
            public int Position { get; set; }
            public AddressParserResult AddressParserResult { get; set; }
            public ObjectStatus Status { get; set; }
            public virtual List<Item> Items { get; set; }

            public Item this[string fieldName]
            {
                get { /* Some code */}
                set { /* Some code */}
            }

            public Item this[int index]
            {
                get { return Items[index]; }
                set { Items[index] = value; }
            }
        }

And I want to be able to serialize/deserialize ObjectCollection. When I try to perform xml-serialization like this:

var xmlSerializer = new XmlSerializer(typeof(ObjectsCollection));
using(var sw = new StreamWriter(fileName, false, Encoding.GetEncoding(CODE_PAGE)))
{
    xmlSerializer.Serialize(sw, objectsCollection);
}
using (var sr = new StreamReader(fileName, Encoding.GetEncoding(CODE_PAGE)))
{
    var deserializedObjectsCollection = xmlSerializer.Deserialize(sr) as ObjectsCollection;
}

I don't get the object I had before. What is wrong?
Thanks in advance!

Upvotes: 1

Views: 149

Answers (1)

Sasha Reminnyi
Sasha Reminnyi

Reputation: 3532

You can't serialize a class that implements IDictionary. Check out this link.

The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.

Upvotes: 3

Related Questions