开发者

How to serialize List<object>

I am writing common functions to serialize the given object and List<object> as follows

public string SerializeObject(Object pObject)// for given object
{
    try
    {
        String XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(typeof(pObject));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
        xs.Serialize(xmlTextWriter, pObject);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
        return XmlizedString;
    }
    catch (Exception e) { System.Console.WriteLine(e); return null; }
}

public string SerializeObject(List<Object> pObject)// for given List<object>
{
    try
    {
        String XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(typeof(pObject));
   开发者_Go百科     XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
        xs.Serialize(xmlTextWriter, pObject);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
        return XmlizedString;
    }
    catch (Exception e) { System.Console.WriteLine(e); return null; }
}

first one is working fine. If I pass any type, it is successfully returning xml string.

CORRECTION: Compilation error has occurred for second one (Error: cannot convert from List<MyType> to List<object>.

I rewrite the second one as follows which solves my problem. Now it is serializing the given List<generic types>.

private string SerializeObject<T>(T source)
{
    MemoryStream memoryStream = new MemoryStream();
    XmlSerializer xs = new XmlSerializer(typeof(T));
    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
    xs.Serialize(xmlTextWriter, source);
    memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
    string XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
    return XmlizedString;
}


https://weblogs.asp.net/rajbk/Contents/Item/Display/345

The relevant code from the article:

private static string SerializeObject<T>(T source)
{
    var serializer = new XmlSerializer(typeof(T));
    using (var sw = new System.IO.StringWriter())
    using (var writer = XmlWriter.Create(sw))
    {
        serializer.Serialize(writer, source);
        return sw.ToString();
    }
}


I have tried your two functions without much trouble. The only thing I changed was this line:

XmlSerializer xs = new XmlSerializer(typeof(pObject));

to this:

XmlSerializer xs = new XmlSerializer(pObject.GetType());

typeof() requires an actual type whereas GetType() returns the type of the object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜