Dynamic XML Serialiser
-
Hi guys, we are back. I have a small problem with xml serialization. Problem: I can serialize an object as the type is know from the object passed in to be serialized, but after this is passed through a webservice, deserialization is a problem, as the type of the object is not known. The objects which are being serialized are all custom objects. Scenario: I have a generic serializer class. The code found below:
/// /// Method to convert a custom Object to XML string /// /// Object that is to be serialized to XML /// XML string public String serializeObject(Object pObject) { try { String XmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlSerializer xs = new XmlSerializer(pObject.GetType()); 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; } } /// /// Method to reconstruct an Object from XML string /// /// /// public Object deserializeObject(String pXmlizedString) { XmlSerializer xs = new XmlSerializer(typeof(Object)); MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); XmlTextReader xmlTextReader = new XmlTextReader(memoryStream); return xs.Deserialize(xmlTextReader); }
When I am serializing the object, this works fine, as I can create a serializer with the object type from the object:
XmlSerializer xs = new XmlSerializer(pObject.GetType());
But when I come to deserialize the object from a string, I see two options which both dont work. Either:
XmlSerializer xs = new XmlSerializer(typeof(Object));
Which gives me a " not expected error" as the serializer obviously doesnt know about my custom class. Or: