(home | about | stats)

pwyky: SerializableDictionary

When you try to serialize a class that either implements or contains a member that implements IDictionary, you'll get an error. I've seen (and used) code that could serialize/deserialize Dictionary<string, string>. But what if you want to serialize Dictionary<string, T>?

public class DictionarySerializer<T> : IXmlSerializable
    {
        public Dictionary<string, T> m_dictionary;
        Type m_type = typeof(T);

        public DictionarySerializer()
        {
            m_dictionary = new Dictionary<string, T>();
        }

        public DictionarySerializer(Dictionary<string, T> dictionary)
        {
            m_dictionary = dictionary;
        }

        public void ReadXml(XmlReader reader)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(string));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(T));

            reader.ReadStartElement();
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                string key = (string)keySerializer.Deserialize(reader);
                T value = (T)valueSerializer.Deserialize(reader);
                m_dictionary.Add(key, value);
            }
        }

        public void WriteXml(XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(string));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(T));

            foreach (string key in m_dictionary.Keys)
            {
                keySerializer.Serialize(writer, key);
                valueSerializer.Serialize(writer, m_dictionary[key]);
            }
        }

        public XmlSchema GetSchema()
        {
            return new XmlSchema();
        }        
    }
www.mobilitytech.com owner. This is a pwyky site.