使用一般处理程序生成 JSON

在 .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;  
        }  
    }  
} 
原文地址:https://www.cnblogs.com/wolfocme110/p/4376226.html