Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / C# 5.0

How to Serialize/Deserialize Objects Programatically?

Rate me:
Please Sign up or sign in to vote.
4.91/5 (10 votes)
12 Aug 2015CPOL1 min read 13.2K   7   7
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

C#
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.

C#
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?

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

Initialize object with some values:

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

Let's use serialize in XML:

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

Deserialize to own type:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
India India
Learning never ends.

Comments and Discussions

 
GeneralGreate Pin
Aladár Horváth13-Aug-15 21:54
professionalAladár Horváth13-Aug-15 21:54 
Generaltnx Pin
Luka13-Aug-15 14:13
Luka13-Aug-15 14:13 
QuestionWhat are the other formats? Pin
Shuby Arora12-Aug-15 20:35
Shuby Arora12-Aug-15 20:35 
AnswerRe: What are the other formats? Pin
Gaurav Aroraa13-Aug-15 4:07
professionalGaurav Aroraa13-Aug-15 4:07 
GeneralRe: What are the other formats? Pin
Shuby Arora14-Aug-15 9:58
Shuby Arora14-Aug-15 9:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.