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