Search code examples
c#xml-serialization

How to Deserialize a custom object having dictionary as a member?


I need to Deserialize object having 2 fields as string and one dictionary, i tried to convert but it throwing error as "Cannot serialize member MVVMDemo.Model.Student.books of type System.Collections.Generic.Dictionary" it is doable when there is no dictionary item in but when i add that dictionary item it fail to convert. throwing error from below line

XmlSerializer serializer = new XmlSerializer(typeof(Student));

Here is my class

public class Student
    {
        private string firstName;
        private string lastName;
        public Dictionary<string, string> books;

        public Dictionary<string, string> Books
        {
            get{return books;}
            set{books = value;}
        }
        public string FirstName
        {
            get{return firstName;}
            set
            {
                if (firstName != value)
                {
                    firstName = value;
                }
            }
        }

        public string LastName
        {
            get { return lastName; }
            set
            {
                if (lastName != value)
                {
                    lastName = value;
                }
            }
        }
    }

Solution

  • You can solve this with Newtonsoft.Json library. To serialize start with converting your object to json, then use DeserializeXNode method:

    var student = new Student()
    {
        FirstName = "FirstName",
        LastName = "LastName",
        Books = new Dictionary<string, string>
        {
            { "abc", "42" },
        }
    };
    
    var json = JsonConvert.SerializeObject(student);
    var xml = JsonConvert.DeserializeXNode(json, "Root");
    var result = xml.ToString(SaveOptions.None);
    // result is "<Root><books><abc>42</abc></books><Books><abc>42</abc></Books><FirstName>FirstName</FirstName><LastName>LastName</LastName></Root>"
    

    To deserialize you can use SerializeXmlNode method:

    var input = "<Root><books><abc>42</abc></books><Books><abc>42</abc></Books><FirstName>FirstName</FirstName><LastName>LastName</LastName></Root>";
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(input);
    var json = JsonConvert.SerializeXmlNode(doc);
    var template = new {Root = (Student) null};
    var result = JsonConvert.DeserializeAnonymousType(json, template);
    // result.Root is an instance of Student class