JSON serialization

In JSON we must explicitly need to put an attribute before each field that needs to be serialized. Also we need to put [DataContract] attribute before the declaration of the class. Here is the sample code JSON serialization -

[DataContract]
public class Employee
{
[DataMember]
private int empId;
[DataMember]
public string empName;
public void SetEmployeeId(int id)
{
empId = id;
}

If you want to ignore any field then simply do not put [DataMember] attribute in front of that property.
To serialize an object to JSON we can use DataContractJsonSerializer class from the namespace System.Runtime.Serialization.Json. Here is the sample code for JSON serialization -

Employee emp = new Employee();
emp.SetEmployeeId(1);
emp.empName = "John";
Stream stream = new FileStream("Emp.json", FileMode.Create);
DataContractJsonSerializer JsonSer = new  DataContractJsonSerializer(typeof(Employee));
JsonSer.WriteObject(stream, Employee);
stream.Close();
The JSON for the employe object is :
{
"empId": 1,
"empName": "John"
}

Following code can be used to read JSON back in the form of object:

Employee emp = new Employee();
Stream stream = new FileStream("Emp.json", FileMode.Create);
DataContractJsonSerializer JsonSer = new  DataContractJsonSerializer(typeof(Employee));
emp = (JsonSer)JsonSer.ReadObject(stream);
stream.Close();

Comments