Mark Beras
Mark Beras

Reputation: 39

How to serialize object to xml with circular dependency in c#?

I've got an object which has a circular dependency

    public class Levels
    {
        public UserDescription user { get; set; }
        public List<Levels> friends {get; set;}

        public Levels(UserDescription user, List<Levels> friends)
        {
           this.user = user;
           this.friends = friends;
        }

        public Levels() { }            
    }

I need to serialize it to xml, so I do the following:

    public string SerializeObject(object obj)
    {
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
        {
            serializer.Serialize(ms, obj);
            ms.Position = 0;
            xmlDoc.Load(ms);
            return xmlDoc.InnerXml;
        }
    }

This code throws an exception System.InvalidOperationException onserializer = new System.Xml.Serialization.XmlSerializer. How can I solve this?

Upvotes: 1

Views: 256

Answers (1)

Mark Beras
Mark Beras

Reputation: 39

The problem was that class UserDescription didn't have an empty constructor.

Upvotes: 2

Related Questions