Saturday, May 18, 2013

Ways of object serialization using C#


       Here i discuss how to serialize object state to a file in different formats, showing you 5 different serialization formats plus how to read object from config file:
  • Binary
  • XML
  • JSON
  • Base64
  • DataContract
  • Object in config file
I took a simple 'Person' class to be used for serializations and 'ConfigPerson' class for object read from config file. I used 'ConfigPerson' class for config read, since 'Person' class cant be used for config specific implementation.

For serialization process i created a component called 'Serializer' with below classes. 
'ObjectSerialize' class contains the nested classes for each serialization format and access methods for these classes. Each nested class inherits from abstract base class 'BaseFileChecker' (for logic reuse: file create & open) and implements 'IFormat' interface (for methods decouple: serialize & deserialize).
Check each nested class for format specific code.



For Testing this component i created a console application.
Pressing 1 shows the below result which is showing 'ConfigPerson' object read from app.config file.
Pressing any other key, prompts for serialization formats (applied on 'Person' class) 

When completed all 5 formats, you will see below files in your folder (folder name hardcoded in console project, change it for your requirement).

 Share your thoughts, alternative solutions and other serialization formats in below comments.

References:
stackoverflow.com/questions/945495/how-can-i-add-a-type-constraint-to-include-anything-serializable-in-a-generic-me
http://www.codeproject.com/Articles/1789/Object-Serialization-using-C
http://stackoverflow.com/questions/980202/how-do-i-find-the-current-executable-filename
http://forums.asp.net/t/1079061.aspx/1

Download:
Download the project solution as Zip file.