準備工作
·Customer類
public class Customer
{
public int Unid { get; set; }
public string CustomerName { get; set; }
public string Memo { get; set; }
public string Other { get; set; }
}
·服務端處理(Json_1.ashx)
Customer customer = new Customer
{ Unid=1,CustomerName="宋江",Memo="天魁星",Other="黑三郎"};
string strJson = Newtonsoft.Json.JsonConvert.SerializeObject(customer);
context.Response.Write(strJson);
(一)Jquery. getJSON
方法定義:jQuery.getJSON( url, data, callback )
通過get請求得到json資料
·url用于提供json資料的位址頁
·data(Optional)用于傳送到伺服器的鍵值對
·callback(Optional)回調函數,json資料請求成功後的處理函數
function(data, textStatus) {
// data是一個json對象
// textStatus will be "success"
this; // the options for this ajax request
(1)一個對象
$.getJSON(
"webdata/Json_1.ashx",
function(data) {
$("#divmessage").text(data.CustomerName);
}
);
向Json_1.ashx位址請求json資料,接收到資料後,在function中處理data資料。 這裡的data的資料是一條記錄,對應于一個customer執行個體,其中的資料以k/v形式存在。即以[object,object]數組形式存在。
{"Unid":1,"CustomerName":"宋江","Memo":"天魁星","Other":"黑三郎"}
是以在通路時,以data.Property來通路,下面以k/v循環來列印這條宋江的記錄:
var tt="";
$.each(data, function(k, v) {
tt += k + ":" + v + "<br/>";
})
$("#divmessage").html(tt);
});
結果:
Unid:1
CustomerName:宋江
Memo:天魁星
Other:黑三郎
(2)對象數組
Ashx檔案(Json_1.ashx)修改:
List<Customer> _list = new List<Customer>();
{ Unid=1,CustomerName="宋江",Memo="天魁星",Other="黑三郎"};
Customer customer2 = new Customer
{ Unid = 2, CustomerName = "吳用", Memo = "天機星", Other = "智多星" };
_list.Add(customer);
_list.Add(customer2);
string strJson = Newtonsoft.Json.JsonConvert.SerializeObject(_list);
它生成的json對象的字元串是:
[{"Unid":1,"CustomerName":"宋江","Memo":"天魁星","Other":"黑三郎"},
{"Unid":2,"CustomerName":"吳用","Memo":"天機星","Other":"智多星"}]
這裡可以看到做為集合的json對象不是再一條記錄,而是2條記錄,是一個[[object,object]]數組:[object,object][object,object],而每個[object,object]表示一條記錄,對應一個Customer,其實也是k/v的形式,而這個v就是一個Customer對象,而這個k是從0開始的索引。
alert(k);
});
這時,k值為0,1……
清單json對象的方法:
var tt = "";
$.each(v,function(kk, vv) {
tt += kk + ":" + vv + "<br/>";
});
Unid:2
CustomerName:吳用
Memo:天機星
Other:智多星
這裡用了嵌套循環,第一個循環用于從List中周遊Customer對象,第二個循環用于從Customer對象中周遊Customer對象的屬性,也就是k/v對。
關于序列化與反序列化請見其它随筆(JSON)
部落格園大道至簡
<a href="http://www.cnblogs.com/jams742003/" target="_blank">http://www.cnblogs.com/jams742003/</a>
轉載請注明:部落格園