您的位置:首页 > Web前端 > JavaScript

使用一般处理程序生成 JSON

2015-03-29 20:18 190 查看
在 .NET 3.5 之后,定义在命名空间 System.Runtime.Serialization.Json 中的 DataContractJsonSerializer 可以帮助我们直接将一个对象格式化成 JSON,或者将一个 JSON 反序列化为一个 .NET 中的对象实例。这样,实现起来可以更加简单。

using System;
using System.Web;

public class Result
{
public int percent { get; set; }
}

public class JsonHandler : IHttpHandler {

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

context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

System.Type type = typeof( Result );
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(type);

Result result = new Result();
result.percent = 80;

serializer.WriteObject(context.Response.OutputStream, result);

}

public bool IsReusable {
get {
return false;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: