简体   繁体   中英

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 on serializer = new System.Xml.Serialization.XmlSerializer . How can I solve this?

问题在于类UserDescription没有空的构造函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM