闡述使用Json傳輸協(xié)議的方式
在正式使用Json之前,首先讓我們簡(jiǎn)要回憶一下XML。XML是“可擴(kuò)展的標(biāo)記語(yǔ)言”的簡(jiǎn)稱,它提供了定義Web中一系列數(shù)據(jù)傳輸協(xié)議的方式,是文本型的,被人們譽(yù)為“完全開(kāi)發(fā)Internet和Web潛力的理想方式”。#t#
得到的數(shù)據(jù)就會(huì)出錯(cuò),如果使用XML的話,又顯得太麻煩,所以,很多時(shí)候使用Json是一種很不錯(cuò)的方式,比如,我們需要用Ajax獲取一組用戶信息,其中包括username,age,sex,address等等;那么組合成的Json字符串為:
- --jquery方式--
- function getUserInfo(id) {
- if (isNaN(id)) { return;}
- $.ajax({
- type: "get",
- url: "AjaxCommonClass.aspx?m=getUserInfoById&id=" + id,
- dataType: "json",
- success: function(data) {
- $("#username").html(data.username);
- $("#age").html(data.age);
- $("#sex").html(data.sex);
- $("#address").html(data.address);
- }
- });
- }
那么如何在后臺(tái)輸出Json格式的字符串呢?最簡(jiǎn)單最原始的方式就是組合字符串:使用System.Text.StringBuilder sb = new System.Text.StringBuilder();sb.Append()方式.最后拼裝: 第二種使用.net freamwork3.0 自帶封裝方法(將對(duì)象序列化成使用Json的字符串)
- public static string Serialize(object obj) {
- if (obj == null) return null;
- System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
- using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
- {
- s.WriteObject(ms, obj);
- return System.Text.Encoding.UTF8.GetString(ms.ToArray());
- }
- }
這樣,我們使用Json直接Response.Write(Serialize(obj))方法即可;客戶端接收到字符串后,會(huì)自動(dòng)解析成JS對(duì)象,下面我就對(duì)升級(jí)前和升級(jí)后的Visual Studio,做一下自己的解析。希望能夠?qū)Υ蠹矣袔椭?/P>