Wednesday, January 21, 2009

Working with JSON using DataContractJsonSerializer class

This class DataContractJsonSerializer is available in the assembly System.ServiceModel.Web.dll.Add a reference to this in your project.
This is the data class which we are going to serialize ie converting from object to JSON format.

public class Employee   
{
public string Name { get; set; }
public string Designation { get; set; }
}


private void btn_Click(object sender, RoutedEventArgs e)        
{
Employee emp=new Employee(){ Name="Joy",Designation="Sr soft engg"};
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Employee));
MemoryStream stream=new MemoryStream();
StreamReader sr = new StreamReader(stream);
ser.WriteObject(stream, emp);
sr.BaseStream.Position = 0;
string s= sr.ReadToEnd();
MessageBox.Show(s);
}

Deserializing ie converting from JSON to object can be done using the method ser.ReadObject()

No comments: