Wednesday 12 January 2011

Serializing and Deserializing Objects into/from XML with Reflection

The Problem: transferring objects over WCF, need to convert objects to string representation and then re-create them on the client end, without explicitly knowing their Type on the client end at compile time.

Found this resource detailing how to serialize and deserialize:

Serialize Object To String

But in that code, it assumes you know what Type to convert the Desearlized object into - but in my case we don't know that until Runtime.

Haven't had to look at it yet but found a good resource for TroubleShooting Common Serialzier Problems

Once the serialized object reached the client via WCF, i then had to read the XML from a Hashtable, desearialize and replace the XML with the relevant object.

Got this exception whilst trying to iterate and amend a collection within the same recursive loop:

"Collection was modified; enumeration operation may not execute."

So used a temporary array to store the key to the entry in the Hashtable that i wanted to update + the new value and new key that i wanted to replace the XML entry with (got the idea here):



// Since we can't iterate and update a Hashtable at same time,
// put the key to the XML in a temp collection
Hashtable updates = new Hashtable();
foreach (string key in response.StructuredData.Keys)
{
if (key.ToString().Contains("xml."))
{
string[] keyParts = key.ToString().Split(new char[] { '.' });
string typeName = keyParts[keyParts.Length - 1];

switch (typeName)
{
case "ensShortList":
ensShortList shortList = DeserializeFromXML(response.StructuredData[key].ToString());
ArrayList newEntry = new ArrayList();
newEntry.Add("ensShortList.ensShortList");
newEntry.Add(shortList);
updates.Add(key, newEntry);
break;
default:
// Type not found
throw new Exception("Unexpected type found in Response.StructuredData XML");
}
}
}

// Use the temp collection to add deserialized objects and remove XML
// to/from StructuredData
foreach (DictionaryEntry entry in updates)
{
ArrayList newEntry = (ArrayList)entry.Value;
response.StructuredData.Add(newEntry[0], newEntry[1]);
response.StructuredData.Remove(entry.Key);
}

No comments:

Post a Comment