DermFrench DermFrench - 9 days ago 6
C# Question

Generic XML Serializer

I'm trying to implement generic XML serializer as described here:
http://blogs.msdn.com/b/field_notes/archive/2008/06/19/the-last-datacontract-serializer-on-earth.aspx

internal static class GenericXmlSerializer<T>
{
public static void WriteObject(T outputObject, string outputFile)
{
using (FileStream writer = new FileStream(outputFile, FileMode.Create))
{
XmlSerializer ser = new XmlSerializer(typeof(T));
ser.Serialize(writer, outputObject);
}
}

public static T ReadObject(string objectData)
{
T deserializedObject = default(T);

using (StringReader reader = new StringReader(objectData))
{
XmlTextReader xmlReader = new XmlTextReader(reader);
XmlSerializer ser = new XmlSerializer(typeof(T));
deserializedObject = (T)ser.Deserialize(xmlReader);
xmlReader.Close();
}

return deserializedObject;
}
}


I then want to call it, but I don't want to hardcode my object types (example hardcoded):

GenericXmlSerializer<MyObjectType>.WriteObject((MyObjectType)data.Payload ,stream);


How do I get those object types at runtime?
e.g. something like:

GenericXmlSerializer<typeof(data.Payload)>.WriteObject((MyObjectType)data.Payload ,stream);

EZI EZI
Answer

Remove T from class, Then you can use as

GenericXmlSerializer.WriteObject(anyObject,"a.xml");

internal static class GenericXmlSerializer
{
    public static void WriteObject<T>(T outputObject, string outputFile)
    {
        using (FileStream writer = new FileStream(outputFile, FileMode.Create))
        {
            XmlSerializer ser = new XmlSerializer(typeof(T));
            ser.Serialize(writer, outputObject);
        }
    }

    public static T ReadObject<T>(string objectData)
    {
        T deserializedObject = default(T);

        using (StringReader reader = new StringReader(objectData))
        {
            XmlTextReader xmlReader = new XmlTextReader(reader);
            XmlSerializer ser = new XmlSerializer(typeof(T));
            deserializedObject = (T)ser.Deserialize(xmlReader);
            xmlReader.Close();
        }

        return deserializedObject;
    }
} 
Comments