none
How to Deserialize a custom object having dictionary as a member? RRS feed

  • Question

  • 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;
    
            [Required, ComplexColumnValueRequiredAttribute]
            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;
                    }
                }
            }
        }


    • Edited by Madan Mishra Monday, July 15, 2019 11:35 AM formatting
    Monday, July 15, 2019 11:29 AM

All replies

  • Please present the code to do this work.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, July 15, 2019 1:25 PM
    Moderator
  • Why XmlSerializer doesn't support Dictionary - https://stackoverflow.com/questions/2911514/why-doesnt-xmlserializer-support-dictionary

    How to Serialize a Dictionary or Hashtable in C# - https://blogs.msdn.microsoft.com/adam/2010/09/10/how-to-serialize-a-dictionary-or-hashtable-in-c/


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, July 15, 2019 2:12 PM
    Moderator
  • Hi Madan,

    Thank you for posting here.

    Based on my search, we could not xmlserialize the dictionary in class directly. However, we could do indirectly.

    Here is a code for your reference.

     public class Student
        {
            private string firstName;
            private string lastName;
            public List<Entry> Entries { get; set; }
    
            public string FirstName
            {
                get
                {
                    return firstName;
                }
    
                set
                {
                    if (firstName != value)
                    {
                        firstName = value;
                    }
                }
            }
    
            public string LastName
            {
                get { return lastName; }
    
                set
                {
                    if (lastName != value)
                    {
                        lastName = value;
                    }
                }
            }
    
           
        }
        public class Entry
        {
            public object Key;
            public object Value;
            public Entry()
            {
            }
    
            public Entry(object key, object value)
            {
                Key = key;
                Value = value;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
    
                List<Entry> list = new List<Entry>();
                list.Add(new Entry { Key="Name",Value="test1"});
                list.Add(new Entry { Key = "Address", Value = "home" });
                list.Add(new Entry { Key = "Workplace", Value = "test1" });
    
                Student s = new Student() { FirstName = "test1", LastName = "test2",Entries=list };
                XmlSerializer xml = new XmlSerializer(typeof(Student));
                TextWriter writer = new StreamWriter("D:\\new.xml");
                xml.Serialize(writer, s);
    
                Console.WriteLine("success");
                Console.ReadKey();
    
    
    
            }
        }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, July 16, 2019 2:28 AM
    Moderator
  • In modern C# and Visual Studio 2019, try an approach like this too:

    public class Student
    {
        private Dictionary<string, string> books;
    
        [Required, ComplexColumnValueRequiredAttribute]
        [XmlIgnore]
        public Dictionary<string, string> Books
        {
            get
            {
                return books;
            }
            set
            {
                books = value;
            }
        }
    
        [XmlArray( "Books" )]
        [XmlArrayItem( "Book" )]
        [EditorBrowsable( EditorBrowsableState.Never )]
        public (string Key, string Value)[ ] InternalBooks
        {
            get
            {
                return Books?.Select( p => (p.Key, p.Value) )?.ToArray( );
            }
            set
            {
                books = value?.ToDictionary( p => p.Key, p => p.Value );
            }
        }
    
        // The members related to First Name and Last Name
        // . . .
    
    }


    The special member InternalBooks is only for serialisation.



    • Edited by Viorel_MVP Tuesday, July 16, 2019 5:12 AM
    Tuesday, July 16, 2019 5:04 AM