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();
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(); 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 MediaFormatter
s, I did not try others.
The post How to Serialize/Deserialize objects programmatically? appeared first on Gaurav-Arora.com.