将对象序列化为XML:IList <customobject>属性导致异常</customobject>

时间:2012-03-26 20:48:30

标签: c# serialization

我正在使用以下函数尝试将对象序列化为XML ..

 public static string SerializeObject<T>(T obj)
        {
            try
            {
                string xmlString = null;
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(typeof(T));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xs.Serialize(xmlTextWriter, obj);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                xmlString = UTF8ByteArrayToString(memoryStream.ToArray()); return xmlString;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

当尝试序列化其中包含IList属性的对象时,我得到以下异常..

Cannot serialize member 'ObjectModel.Order.LineItems' of type 'System.Collections.Generic.IList

有人可以帮我改变我的功能以适应这种情况吗?

有什么我可以用现有的代码来查看输入对象。如果它的Ilist类型将其更改为List?如果可能的话,somoeone可以帮助我编写代码吗?

3 个答案:

答案 0 :(得分:6)

对此没有很好的解决方案,只有在这种情况下使用类似List<T>的具体类型的解决方法 - 您可以将现有属性更改为List<T>或添加仅用于类型List<T>的序列化(以及XML - 忽略您现有的属性)。

答案 1 :(得分:0)

XmlSerializer不处理类型IList<T>的属性。有一些解决方法,其中最直接的方法是更改​​属性的类型:

https://www.google.com/search?q=xmlserializer+ilist

答案 2 :(得分:-1)

Xml输出有多重要?二进制格式更容易适应。如果需要,你可以将输出转换为base64字符串。

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter(v=vs.71).aspx