interviews.dotnetthread.com

↑ Grab this Headline Animator

Tuesday, October 20, 2009

JSON Serialization in VS 2008

Say we need to convert serialize C# object to JSON string and transfer that to client side to be used in Javascript. DataContract attribute is added to a class and DataMember attribute is added for all members that need be serialized.


[DataContract]
public class Employee
{
#region "Private Variables"
private string name = string.Empty;
private string id = string.Empty;
#endregion

#region "Public Properties"
[DataMember]
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
[DataMember]
public string ID
{
get
{
return this.id;
}

set
{
this.id = value;
}
}
}

Now in order to convert the above mentioned class object to JSON string use below code.

Employee obj = new Employee();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
ms.Flush();
byte[] bytes = ms.GetBuffer();
string jsonString = Encoding.UTF8.GetString(bytes, 0, bytes.Length).Trim('\0');
return jsonString;
}

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.

 

Latest Articles