How to Serialize/Deserialize objects programmatically?

I have received one email quoting above question which was related to my previous talk on ASP.NET MVC for Beginners Series @csharpcorner Chapter Delhi Developers Day.

There are many serialize and deserialize library available which provide us the facility to do the same in our preferred MediaType. Like for JSON serialization/deserialization there is most known library available is "NewtonSoft' and JSON or JSON2 Javascript APIs.

In this short code tutorial we will create our custom method with the use of Streaming. I am not going to describe all and each code snippet as it is understandable from its own code:

Our custom methods
  1. public string SerializeTo<T>(MediaTypeFormatter custFormatter, T objValue)  
  2. {  
  3.     var stream = new MemoryStream();  
  4.     var content = new StreamContent(stream);  
  5.   
  6.     custFormatter.WriteToStreamAsync(typeof(T), objValue, stream, content, null).Wait();  // why wait?  
  7.       
  8.     stream.Position = 0;  
  9.     return content.ReadAsStringAsync().Result;  
  10. }  
Above, will accept MediaType viz. xml, json, plain etc. and a Value of Type T, it would be your custom object 
  1. public T DeserializeFrom<T>(MediaTypeFormatter custFormatter, string str) where T : class  
  2. {  
  3.     Stream stream = new MemoryStream();  
  4.     StreamWriter writer = new StreamWriter(stream);  
  5.     writer.Write(str);  
  6.     writer.Flush(); //why Flush ?  
  7.     stream.Position = 0;  
  8.    
  9.     return custFormatter.ReadFromStreamAsync(typeof(T), stream, nullnull).Result as T;  
  10. }  
Above, will deserilize formatted string to your provided Type. Type would be your custom object type.
 
How to use?
Lets say we have following object with us:
  1. public class Author  
  2. {  
  3.   public string Name {get;set;}  
  4.   public string Category {get;set;}  
  5.   public int Level {get;set};  
  6. }  
Initialize object with some values:
  1. var author = new Author {  
  2.              Name = "Gaurav Kumar Arora",  
  3.              Category = "Silver",  
  4.              Level = 1  
  5. };  
Lets use serialize in XML
  1. var xmlFormatter = new XmlMediaTypeFormatter();  
  2. var xmlString = SerializeTo(xmlFormatter, author);  
Deserialize to own type
  1. var originalAuthor = DeserializeFrom<Author>(xmlFormatter, xmlString);  
Note: You can also try other available MediaFormatter, I did not try others ;)