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.

3 comments:

Unknown said...

This is a good idea, but why not using SerializableDictionary as implemented in Paul Welter's Weblog: http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx ?

Alex Pinsker said...

p.s.
Please read 'Tuple' as 'KeyValuePair' in my post :)
As I had discussion with a friend of my on why it can't be serializable - I want to add that it's since KeyValuePair has no set properties and XmlSerializer by design doesn't serialize read-only properties.

Alex Pinsker said...

Hey Boris, thanks for your reply and reference to the Paul's solution! I think his solution is better in the way that it provides 1st class serializable dictionary. On the other hand - it's more code/more complexity.

p.s. your blog profile-sharing is disabled, so I can't get to your blog from your comment.