Wednesday, April 11, 2007

Generics collection serializer


Here is small utility class to serialize/deserialize generics collection... My usage of it is passing of multiple parameters to a web service at once.



using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Xml.Serialization;
public class CollectionSerializer<TKey, TValue>
{
public static void Serialize(TextWriter writer, IDictionary<TKey, TValue> dictionary)
{
List<ListEntry<TKey, TValue>> entries = new List<ListEntry<TKey, TValue>>(dictionary.Count);
foreach (TKey key in dictionary.Keys)
{
entries.Add(new ListEntry<TKey, TValue>(key, dictionary[key]));
}

XmlSerializer serializer = new XmlSerializer(typeof(List<ListEntry<TKey, TValue>>));
serializer.Serialize(writer, entries);
}

public static void Deserialize(TextReader reader, IDictionary dictionary)
{
dictionary.Clear();
XmlSerializer serializer = new XmlSerializer(typeof(List<ListEntry<TKey, TValue>>));
List<ListEntry<TKey, TValue>> list = (List<ListEntry<TKey, TValue>>)serializer.Deserialize(reader);

foreach( ListEntry<TKey, TValue> entry in list )
{
dictionary[entry.Key] = entry.Value;
}
}

public class ListEntry<TKeyEntry, TValueEntry>
{
public ListEntry()
{}

public ListEntry(TKeyEntry key, TValueEntry value)
{
Key = key;
Value = value;
}

public TKeyEntry Key;
public TValueEntry Value;
}
}
Please note that standard Tuple type can't be used instead of custom ListEntry as it can't be serialized.