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
- 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;
- }
- 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;
- }
How to use?
Lets say we have following object with us:
- public class Author
- {
- public string Name {get;set;}
- public string Category {get;set;}
- public int Level {get;set};
- }
- var author = new Author {
- Name = "Gaurav Kumar Arora",
- Category = "Silver",
- Level = 1
- };
- var xmlFormatter = new XmlMediaTypeFormatter();
- var xmlString = SerializeTo(xmlFormatter, author);
- var originalAuthor = DeserializeFrom<Author>(xmlFormatter, xmlString);

Join the conversation! Your thoughts help the community grow.