Skip to main content

Posts

Showing posts from January, 2015

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.W