How to serialize object into JSON Format?

Raja
Posted by Raja under ASP.NET AJAX category on | Views : 5802
To searialize object into JSON format, use following method.

Namespace to use System.Runtime.Serialization.Json;

private static string SerializeObjectIntoJson(Person p)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(p.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, p);
ms.Flush();

byte[] bytes = ms.GetBuffer();
string jsonString = Encoding.UTF8.GetString(bytes, 0, bytes.Length).Trim('\0');
return jsonString;
}
}


Note above method and Namespace is accessible only in Website or Web application project not in class library.

Reference: http://www.dotnetfunda.com/articles/article454-using-pagemethods-and-json-in-aspnet-ajax.aspx

Comments or Responses

Posted by: Poster on: 8/26/2009 Level:Starter | Status: [Member]
Thanks, this is what I was looking for.

Regards

Login to post response