views:

27

answers:

1

Solved: code below is not causing an infinite loop as I thought. the loop was in the code calling the deserialization. this posted code works just fine

I am trying to serialize and deserialize to xml the following object

public class MessageObjectCollection : List<MessageObject>
{
    public string Serialize()
    {
        return XmlObjectSerializer.SerializeObject(this);
    }

    public static MessageObjectCollection DeSerialize(string serializedPriceHistory)
    {
        return XmlObjectSerializer.DeserializeObject<MessageObjectCollection>(serializedPriceHistory);
    }
}

The MessageObject class looks like this

public class MessageObject
{
    public string Title;
    public MessageObjectCollection Responses;
}

So if I have a instance of messageobjectcollection that looks like:

var msgColl = new MessageObjectCollection
    {
         new MessageObject
              {
                   Title = "Hello",
                   Responses = new MessageObjectCollection
                        {
                             new MessageObject
                                  {
                                      Title = "hi",
                                      Responses = null
                                  }
                        }
              }
    }

I can serialize this just fine by calling var xml = msgColl.Serialize();

However when I try to deserialize this by calling var msgColl = new MessageObjectCollection().Deserialize(xml);

I get an stack overflow exception in the deserialization method:

public static T DeserializeObject<T>(string xml)
{
    T result;
    var ser = new XmlSerializer(typeof(T));
    var buffer = StringToUTF8ByteArray(xml);
    using (var stream = new MemoryStream(buffer, 0, buffer.Length))
    {
        result = (T) ser.Deserialize(stream);
    }
    return result;
}

Anyone know what I'm doing wrong?

A: 

Im not sure if its relevant to the problem but as the Deserialize method is static shouldn't you be calling...

var msgColl = MessageObjectCollection.Deserialize(xml);

instead of...

var msgColl = new MessageObjectCollection().Deserialize(xml);

??

barrylloyd
Yes, your right of course. This wasn't the problem though. This code works just fine, the infinite loop was happening not in this code but upstream in the code calling the deserialization....
Richard Brink
Ok, glad you figured it out.
barrylloyd