How to Serialize/Deserialize objects programatically?

In this short code tutorial we will create our custom method with the use of Streaming and will see how serialize and deserialize happened.

I have received one email quoting above question, which was related to my recent talk on ASP.NET MVC for Beginners Series in Delhi, India.

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

public string SerializeTo<T>(MediaTypeFormatter custFormatter, T objValue)  
{  
    var stream = new MemoryStream();  
    var content = new StreamContent(stream);  
  
    custFormatter.WriteToStreamAsync(typeof(T), objValue, stream, content, null).Wait();  // why wait?  
      
    stream.Position = 0;  
    return content.ReadAsStringAsync().Result;  
} 

Above, will accept MediaType viz. xml, json, plain etc. and a Value of Type T, it would be your custom object

public T DeserializeFrom<T>(MediaTypeFormatter custFormatter, string str) where T : class  
{  
    Stream stream = new MemoryStream();  
    StreamWriter writer = new StreamWriter(stream);  
    writer.Write(str);  
    writer.Flush(); //why Flush ?  
    stream.Position = 0;  
   
    return custFormatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;  
} 

Above, will deserilize formatted string to your provided Type. Type would be your custom object type.

How to use?

public class Author  
{  
  public string Name {get;set;}  
  public string Category {get;set;}  
  public int Level {get;set};  
}

Initialize object with some values:

var author = new Author {  
             Name = "Gaurav Kumar Arora",  
             Category = "Silver",  
             Level = 1  
}; 

Lets use serialize in XML

var xmlFormatter = new XmlMediaTypeFormatter();  
var xmlString = SerializeTo(xmlFormatter, author);

Deserialize to own type

var originalAuthor = DeserializeFrom<Author>(xmlFormatter, xmlString);

Note: You can also try other available MediaFormatter, I did not try others 😉

Leave A Reply