Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Serialize/Deserialize Objects Programatically?

0.00/5 (No votes)
12 Aug 2015 1  
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 the 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 libraries available which provide us the facility to do the same in our preferred MediaType. Like for JSON serialization/deserialization, the 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 deserialize 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  
}; 

Let's 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 MediaFormatters, I did not try others. ??

The post How to Serialize/Deserialize objects programmatically? appeared first on Gaurav-Arora.com.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here