How to Serialize a non-serializable class in .Net?

Although we can use BinarySerializer to serialize objects, the constraint is that we have to mark the class as [Serializable].

This could not be feasible as we have to deal with different kinds of objects which contains other types.

The Solution

Use XmlSerializer for the purpose.

  private void Button_Click(object sender, EventArgs e)

        {

            Book book = new Book();

            book.Title = "Rich Dad Poor Dad";

            book.ReleaseDate = new DateTime(2000, 1, 1);

            book.Author = new Author() { Name = "Robert Kiyosaki", Email = "rkiyosaki@richdad.com" };

 

            book.AuthorList = new List<Author>();

            book.AuthorList.Add(book.Author);

            book.AuthorList.Add(book.Author);

 

            book.Price = 6.9f;

 

            List<Book> books = new List<Book>() { book, book };

 

            // Serialize

            SerializeToXML(books);

 

            // Deserialize

            books = DeserializeFromXML();

        }

 

        public void SerializeToXML(List<Book> movies)

        {

            XmlSerializer serializer = new XmlSerializer(typeof(List<Book>));

            TextWriter textWriter = new StreamWriter(@"C:movie.xml");

            serializer.Serialize(textWriter, movies);

            textWriter.Close();

        }

 

        public List<Book> DeserializeFromXML()

        {

            XmlSerializer deserializer = new XmlSerializer(typeof(List<Book>));

            TextReader textReader = new StreamReader(@"C:movie.xml");

            List<Book> movies;

            movies = (List<Book>)deserializer.Deserialize(textReader);

            textReader.Close();

 

            return movies;

        } 

 

        // Classes

 

        public class Book

        {

            public string Title

            { get; set; }

 

            public float Price

            { get; set; }

 

            public DateTime ReleaseDate

            { get; set; }

 

            public Author Author { get; set; }

 

            public List<Author> AuthorList { get; set; }

        }

 

        public class Author

        {

            public string Name { get; set; }

            public string Email { get; set; }

        }

Leave a Reply

Your email address will not be published. Required fields are marked *