Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary Data Serialization in C#

I want to convert my dictionary data into XML. I am trying to use XML serialization but I am getting an error. Below is my code.

class Program
{

    static void Main(string[] args)
    {
        Dictionary<int, AddressDetails> objDic = new Dictionary<int, AddressDetails>();
        for (int i = 1; i <= 5; i++)
        {
            AddressDetails obj = new AddressDetails();
            obj.HouseNo = i;
            obj.StreetName = "New Street One " + i;
            obj.City = "New Delhi One " + i;
            objDic.Add(i, obj);
        }

        string str = Utility.GetXMLFromObject(objDic);
    }

}

public class AddressDetails 
{
    public int HouseNo { get; set; }
    public string StreetName { get; set; }
    public string City { get; set; }
    private string PoAddress { get; set; }
}

public static class Utility
{
    public static string GetXMLFromObject(object o)
    {
        StringWriter sw = new StringWriter();
        XmlTextWriter tw = null;
        try
        {
            XmlSerializer serializer = new XmlSerializer(o.GetType());
            tw = new XmlTextWriter(sw);
            serializer.Serialize(tw, o);
        }
        catch (Exception ex)
        {
            //Handle Exception Code
        }
        finally
        {
            sw.Close();
            if (tw != null)
            {
                tw.Close();
            }
        }
        return sw.ToString();
    }
}

Error Code line : XmlSerializer serializer = new XmlSerializer(o.GetType());

Error Description :

The type System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[ConsoleApplication5.AddressDetails, ConsoleApplication5, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] is not supported because it implements IDictionary.

Please suggest.

like image 269
KiddoDeveloper Avatar asked Aug 11 '26 15:08

KiddoDeveloper


1 Answers

Try the solutions explained in the link below:

http://theburningmonk.com/2010/05/net-tips-xml-serialize-or-deserialize-dictionary-in-csharp/

You have to either use DataContract Serialization instead of XmlSerialization or use a custom Dictionary type.

like image 118
sachin Avatar answered Aug 14 '26 08:08

sachin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!