Follow us on X (Twitter)  Like us on Facebook  Connect with us on LinkedIn  Subscribe to our YouTube Channel  Subscribe to our WhatsApp Group

Serialization and deserialization of .NET objects made easy using various serializer classes that it provides. But serialization of Dictionary object is not that much easy. For this, you have to create a special Dictionary class which is able to serialize itself. The serialization technique might be different in different business cases.

 

Today, let’s discuss how to implement the same with a sample. Code is shared in the post, which you can use in your application. Continue reading and let me know if you have any other approaches.

 

Dictionary serialization using C# (www.kunal-chowdhury.com)

 

To serialize a dictionary object, you need to first create a custom dictionary class, implementing IXmlSerializable interface. The interface contains three methods named GetSchema, ReadXml, WriteXml. You need to implement the logic in those methods. Below is the complete code for your reference:

 

[XmlRoot("Languages")]
public class LanguageSettings<TKey, TValue> : Dictionary<TKey, TValue>, 
                                              IXmlSerializable
{
    public XmlSchema GetSchema() { return null; }
 
    public void ReadXml(XmlReader reader)
    {
        if(reader.IsEmptyElement) { return; }
 
        reader.Read();
        while (reader.NodeType != XmlNodeType.EndElement)
        {
            object key = reader.GetAttribute("Title");
            object value = reader.GetAttribute("Value");
            this.Add((TKey)key, (TValue)value);
            reader.Read();
        }
    }
 
    public void WriteXml(XmlWriter writer)
    {
        foreach (var key in this.Keys)
        {
            writer.WriteStartElement("Language");
            writer.WriteAttributeString("Title", key.ToString());
            writer.WriteAttributeString("Value", this[key].ToString());
            writer.WriteEndElement();
        }
    }
}

 

In the above code snippet you can observe that, we are serializing the object as XML attributes. In case you have a different business need, you can change it to root element type.

 

Once your custom dictionary class is ready, you can start writing your dictionary object as XML file. Below is the logic to implement the same with XmlSerializer API:

 

XmlSerializer serializer = new XmlSerializer(typeof(LanguageSettings<string, string>));
TextWriter textWriter = new StreamWriter(@"languages.xml");
serializer.Serialize(textWriter, settings);
textWriter.Close();

 

You can also use XmlSerializer to read the XML and deserialize it to your dictionary object. You need to use TextReader to read the input stream from the XML file. Here’s the code snippet:

 

XmlSerializer serializer = new XmlSerializer(typeof(LanguageSettings<string, string>));
TextReader textReader = new StreamReader(@"languages.xml");
LanguageSettings<string, string> settings = 
                  (LanguageSettings<string, string>)serializer.Deserialize(textReader);
textReader.Close();

 

I hope that the post was useful and you would be able to use the shared code snippet in your project directly to serialize/deserialize a Dictionary object to/fro XML file. Please share your feedback about the post in the below comment section. If you have already implemented the same in different way, would love to see the same. Do share with us.

 

Have a question? Or, a comment? Let's Discuss it below...

dhgate

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.