ASP.NET AJAX的JSON序列化和反序列化


  本文标签:JSON序列化和反序列化 ASP.NET AJAX

  JSON序列化和反序列化

  1. POST /Ajax/ZipCodeService.asmx/GetCityAndState HTTP/1.1  
  2. Accept: */*  
  3. Accept-Language: en-us  
  4. Referer: http://localhost:1997/Ajax/ZipCodePage.aspx  
  5. UA-CPU: x86  
  6. Accept-Encoding: gzip, deflate  
  7. User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; ...)  
  8. Host: localhost:1997  
  9. Content-Length: 15  
  10. Connection: Keep-Alive  
  11. Cache-Control: no-cache  
  12. {"zip":"98052"}  
  13. HTTP/1.1 200 OK  
  14. Server: ASP.NET Development Server/8.0.0.0  
  15. Date: Fri, 29 Dec 2006 21:06:17 GMT  
  16. X-AspNet-Version: 2.0.50727  
  17. Cache-Control: private, max-age=0 
  18. Content-Type: application/json; charset=utf-8  
  19. Content-Length: 16  
  20. Connection: Close  
  21.  
  22. {"REDMOND", "WA"} 

  
JSON 是一个正在崭露头角的行业标准序列化格式  。它还是被 ASP.NET AJAX 使用的本机格式  。Microsoft AJAX Library 的 Sys.Serialization.JavaScriptSerializer 类支持在客户端进行 JSON序列化和反序列化  。System.Web.Script.Serialization.JavaScriptSerializer 类支持在服务器上进行 JSON序列化和反序列化  。

  并非所有类型均与 JSON 兼容  。例如,JSON 不能处理具有循环引用的对象  。当您需要返回不能与 JSON 兼容的复杂数据类型时,其实您可以使用 ASP.NET AJAX 的 ScriptMethod 属性将返回类型序列化为 XML  。这个技术对返回 XML 数据的方法也很有用,如下所示:

  1. [ScriptMethod (ResponseFormatResponseFormat=ResponseFormat.Xml)]  
  2. public XmlDocument GetData()  
  3. {  
  4.   ...  

  此外,您还可以构建和注册自定义 JSON 转换器,它允许将通常不能与 JSON 兼容的类型序列化和反序列化  。ASP.NET AJAX January Futures CTP 包含三个这样的转换器:一个针对 DataSet,一个针对 DataTable,还有一个针对 DataRow  。