Conversion of JSON string to object using generic function in c#
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is using widely in data exchange
Generic functions
Generic methods have type parameters. They provide a way to parameterize the types used in a method. This means you can provide only one implementation and call it with different types. Generic methods require an unusual syntax form for more information on generic methods Click here
using System.Runtime.Serialization.Json;
public static class Utilities
{
public static T Deserialize<T>(string jsonString)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}
Above function accept string and return type and convert it to object as specified in return type.
Calling generic function
List<.RequestsType>objLstResponse=new List<.RequestsType>();
objLstResponse=Utilities.Deserialise<List<.RequestsType>>(response);
By this i got idea of generic functions
ReplyDeleteNice one it really helped me a lot ..
Thanks for reply
Deletecan u tell me how to create xml from an object
ReplyDeletethanks for you interest. I had recently add new post
Deletehttp://ishareidea.blogspot.in/2012/05/object-to-xml.html
Perfect
ReplyDelete