.NET Generic Handler(ashx) Object to JSON Serialization


public class jsonSample : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";

Person p = new Person();
p.name = "Richard";
p.address.Add("Taipei");
p.address.Add("US");

// .NET 3.5 & 4 solution
// Reference : http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
context.Response.Write(serializer.Serialize(p));

// Json.NET solution
// Reference : http://json.codeplex.com/
context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(p));

/* Result:
*
* {"name":"Richard","address":["Taipei","US"]}
*
*/
}

public bool IsReusable
{
get
{
return false;
}
}
}

public class Person
{
public List<string> address = new List<string>();
public string name;
}

沒有留言:

張貼留言