首先创建一个一般处理程序“ResponseJson.ashx”,手动拼接字符串返回Json格式:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
List<cityInfo> cityInfos = new List<cityInfo>()
{
new cityInfo(){cityID=1,cityName="北京"},
new cityInfo(){cityID=2,cityName="上海"},
new cityInfo(){cityID=3,cityName="南京"},
new cityInfo(){cityID=4,cityName="深圳"},
new cityInfo(){cityID=5,cityName="广州"}
};
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (cityInfo cityInfo in cityInfos)
{
sb.Append("{");
sb.AppendFormat("\"cityID\":{0},\"cityName\":\"{1}\"", cityInfo.cityID, cityInfo.cityName);
sb.Append("}");
sb.Append(",");
}
string str = sb.ToString().TrimEnd(',');
str += "]";
context.Response.Write(str);
// 或者将对象序列化成Json格式 和拼接相比这种方式较为死板
//System.Web.Script.Serialization.JavaScriptSerializer JSSerializer = new JavaScriptSerializer();
//string Json = JSSerializer.Serialize(cityInfos);
//context.Response.Write(Json);
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class cityInfo
{
public string cityName
{
get;
set;
}