本篇文章主要介绍如何在Ajax的客户端与服务端之间传送JSON格式的数据。那么我们先来说说什么是JSON吧。
JSON,即是JavaScript对象标记法,英文名称是JavaScript Object Notation,简称JSON ,是 JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999 的子集合,是从JavaScript的object initializer扩展而来的一种文本格式标记法,是作为数据交换之用的。
相对于XML,JSON在表示资料时更加简洁,例如一个表示帐户的资料,XML中可能表示:
[c-sharp] view plaincopy
- <account>
- <number>123456</number>
- <name>Justin</name>
- <balance>1000</balance>
- </account>
而使用JSON可以这样表示:
[c-sharp] view plaincopy
- var account = {
- number : "123456",
- name: "Justin",
- balance: "1000"
- };
下面举一个例子说明。
例如你可以把JSON表示法以POST发送至服务端,例如:
[c-sharp] view plaincopy
- var xmlHttp;
- function createXMLHttpRequest() {
- if (window.XMLHttpRequest) {
- xmlHttp = new XMLHttpRequest();
- }
- else if (window.ActiveXObject) {
- xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- }
- function prepareJSON() {
- var firstname = document.getElementById("FirstName").value;
- var lastname = document.getElementById("LastName").value;
- var person = new Object();
- person.FirstName = firstname;
- person.LastName = lastname;
- return person.toJSONString();
- }
- function handleAccount() {
- var json = prepareJSON();
- var url = "Handler1.ashx?timeStamp" + new Date().getTime();
- createXMLHttpRequest();
- xmlHttp.onreadystatechange = handleStateChange;
- xmlHttp.open("POST", url);
- xmlHttp.setRequestHeader("Content-Type",
- "application/x-www-form-urlencoded");
- xmlHttp.send(json);
- }
- function handleStateChange() {
- if (xmlHttp.readyState == 4) {
- if (xmlHttp.status == 200) {
- document.getElementById("response").innerHTML = xmlHttp.responseText;
- var json = eval('(' + xmlHttp.responseText + ')');
- }
- }
- }
这个这个程序简单地将用户姓名包装成一个对象,并使用toJSONString()将之转换为JSON格式,之后POST至服务端。在服务端的程序如下所示:
Handler1中的中ProcessRequest代码如下:
[c-sharp] view plaincopy
- public void ProcessRequest(HttpContext context)
- {
- HttpRequest request = context.Request;
- Stream stream = request.InputStream;
- string json = string.Empty;
- string responseJson = string.Empty;
- if (stream.Length != 0)
- {
- StreamReader streamReader = new StreamReader(stream);
- json = streamReader.ReadToEnd();
- Person person = JSONHelper.Deserialize<Person>(json);
- person.FirstName = "FN";
- person.LastName = "LN";
- responseJson = JSONHelper.Serialize<Person>(person);
- }
- if (!string.IsNullOrEmpty(responseJson))
- {
- context.Response.ContentType = "text/plain";
- context.Response.ContentType = "UTF-8";
- context.Response.Write(responseJson);
- }
- }
另外,在服务端还需要对客户端传过来的JSON数据进行反序列化为一个Person对象实例,序列化与反序列化代码如下:
[c-sharp] view plaincopy
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Json;
- using System.IO;
- using System.Text;
- public class JSONHelper
- {
- public static string Serialize<T>(T obj)
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
- MemoryStream ms = new MemoryStream();
- serializer.WriteObject(ms, obj);
- string retVal = Encoding.Default.GetString(ms.ToArray());
- return retVal;
- }
- public static T Deserialize<T>(string json)
- {
- MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
- T obj = (T)serializer.ReadObject(ms);
- ms.Close();
- return obj;
- }
- }
此外,需要一个简单的Person类的定义,
[c-sharp] view plaincopy
- using System.Runtime.Serialization;
- namespace HelloAjaxJson
- {
- [DataContract]
- public class Person
- {
- public Person() { }
- public Person(string firstname, string lastname)
- {
- this.FirstName = firstname;
- this.LastName = lastname;
- }
- [DataMember]
- public string FirstName { get; set; }
- [DataMember]
- public string LastName { get; set; }
- }
- }
转至: http://blog.csdn.net/starandtina/article/details/4785552