Search All Articles Submit your Website or Blog to A New Internet Library
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;
}
Subscribe to:
Post Comments (Atom)
Also Read other Top Articles
- JSON Serialization in VS 2008
- Implementing Forms Authentication in Silverlight Application.
- Making GridView Rows or Individual Cells Clickable and Selectable.
- Enabling browser back button for GridView Paging and Sorting in Ajax 1.1 and 3.5 (using Visual Studio 2005/ Visual studio 2008)
- How to pass values from User Control to Page or calling Page methods from User Control.
- What is WCF?
- New features in C# 4.0
- C# to VB.NET and VB.NET to C# online free converter tools.


0 comments:
Post a Comment
Post your comments/questions/feedback for this Article.