Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
        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;
}
like image 932
afin Avatar asked Apr 20 '10 23:04

afin


1 Answers

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();
    }
}
like image 51
Raj Kaimal Avatar answered Oct 01 '22 14:10

Raj Kaimal