Tuesday, 22 May 2012

JSON Conversion

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);



4 comments:

  1. By this i got idea of generic functions
    Nice one it really helped me a lot ..

    ReplyDelete
  2. can u tell me how to create xml from an object

    ReplyDelete
    Replies
    1. thanks for you interest. I had recently add new post
      http://ishareidea.blogspot.in/2012/05/object-to-xml.html

      Delete