XmlSerializer is the serializer in .NET for many years.The Serialize and Deserialize methods of XmlSerializer
are used to Serialization
and Deserialization respectively.
DataContractSerializer is new in .NET 3.0.The WCF services
by default uses the DataContractSerializer
for Serialization.It is faster than XmlSerializer.
namespace
Serialization
{
public
class Main
{
//convert the object to json
public void Serialize()
{
//create class object
ClassRoom objClass = new
ClassRoom();
//assign name
objClass.Name = "MCA";
//list of students
List<Student>
objList = new List<Student>();
//create student object
Student objStudent = new
Student();
//assign name
objStudent.Name = "Sekhar";
//assign Age
objStudent.Age =
24;
//student birthday
objStudent.DOB = DateTime.Now;
//student status
objStudent.Status =
Status.UnEmployed;
//adding student to list
objList.Add(objStudent);
//assign student object
objClass.Students =
objList.ToArray();
//json serializer
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ClassRoom));
//memory stream
MemoryStream
ms = new MemoryStream();
//write object to stream
ser.WriteObject(ms,
objClass);
//read the json string from stream
string json = Encoding.Default.GetString(ms.ToArray());
}
//convert the json to object
public void DeSerialize()
{
//json string
string Json = "{\"Name\":\"MCA\",\"Students\":[{\"Age\":24,\"DOB\":\"\\/Date(1326975142299+0530)\\/\",\"Name\":\"Sekhar\",\"Status\":2}]}";
//json serializer
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ClassRoom));
//memory stream for json string
MemoryStream ms = new
MemoryStream(Encoding.UTF8.GetBytes(Json));
//read object from strem
ClassRoom objClassRoom = (ClassRoom)ser.ReadObject(ms);
}
}
[DataContract]
public
class ClassRoom
{
//class name
[DataMember]
public string Name { get; set; }
//list of students
[DataMember]
public Student[] Students { get; set; }
}
[DataContract]
public
class Student
{
//student name
[DataMember]
public string Name { get; set; }
//student age
[DataMember]
public int Age { get; set; }
//student birthday
[DataMember]
public DateTime DOB { get; set; }
//student status
[DataMember]
public Status Status { set; get; }
}
//enum
for student status
public
enum Status
{ Employed, UnEmployed, Student };
}
Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com
No comments:
Post a Comment