How to serialize object into JSON Format?

Posted by Raja under ASP.NET AJAX category on | Views : 6293
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);

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.


Comments or Responses

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


Login to post response