講完了分頁功能,這一節我們先不急著實現新的功能。來簡要介紹下Abp中Json的用法。為什么要在這一節講呢?當然是做鋪墊啊,后面的系列文章會經常和Json這個東西打交道。
一、Json是干什么的
JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。 易于人閱讀和編寫。同時也易于機器解析和生成。JSON采用完全獨立于語言的文本格式,但是也使用了類似于C語言家族的習慣(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 這些特性使JSON成為理想的數據交換語言。
Json一般用于表示:
名稱/值對:
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
數組:
{ "people":[ {"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}, {"firstName":"Jason","lastName":"Hunter","email":"bbbb"}, {"firstName":"Elliotte","lastName":"Harold","email":"cccc"} ]}
二、Asp.net Mvc中的JsonResult
Asp.net mvc中默認提供了JsonResult來處理需要返回Json格式數據的情況。
一般我們可以這樣使用:
public ActionResult Movies(){ var movies = new List<object>(); movies.Add(new { Title = "Ghostbusters", Genre = "Comedy", ReleaseDate = new DateTime(2017,1,1) }); movies.Add(new { Title = "Gone with Wind", Genre = "Drama", ReleaseDate = new DateTime(2017, 1, 3) }); movies.Add(new { Title = "Star Wars", Genre = "Science Fiction", ReleaseDate = new DateTime(2017, 1, 23) }); return Json(movies, JsonRequestBehavior.AllowGet);}
其中Json()是Controller基類中提供的虛方法。
返回的json結果格式化后為:
[ { "Title": "Ghostbusters", "Genre": "Comedy", "ReleaseDate": "http://Date(1483200000000)//" }, { "Title": "Gone with Wind", "Genre": "Drama", "ReleaseDate": "http://Date(1483372800000)//" }, { "Title": "Star Wars", "Genre": "Science Fiction", "ReleaseDate": "http://Date(1485100800000)//" }]
仔細觀察返回的json結果,有以下幾點不足:
返回的字段大小寫與代碼中一致。這就要求我們在前端中也要與代碼中用一致的大小寫進行取值(item.Title,item.Genre,item.ReleaseDate)。
不包含成功失敗信息:如果我們要判斷請求是否成功,我們要手動通過獲取json數據包的length獲取。
返回的日期未格式化,在前端還需自行格式化輸出。
三、Abp中對Json的封裝
所以Abp封裝了AbpJsonResult繼承于JsonResult,其中主要添加了兩個屬性:
CamelCase:大小駝峰(默認為true,即小駝峰格式)
Indented :是否縮進(默認為false,即未格式化)
并在AbpController中重載了Controller的Json()方法,強制所有返回的Json格式數據為AbpJsonResult類型,并提供了AbpJson()的虛方法。
/// <summary>/// Json the specified data, contentType, contentEncoding and behavior./// </summary>/// <param name="data">Data.</param>/// <param name="contentType">Content type.</param>/// <param name="contentEncoding">Content encoding.</param>/// <param name="behavior">Behavior.</param>protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior){ if (_wrapResultAttribute != null && !_wrapResultAttribute.WrapOnSuccess) { return base.Json(data, contentType, contentEncoding, behavior); } return AbpJson(data, contentType, contentEncoding, behavior);}protected virtual AbpJsonResult AbpJson( object data, string contentType = null, Encoding contentEncoding = null, JsonRequestBehavior behavior = JsonRequestBehavior.DenyGet, bool wrapResult = true, bool camelCase = true, bool indented = false){ if (wrapResult) { if (data == null) { data = new AjaxResponse(); } else if (!(data is AjaxResponseBase)) { data = new AjaxResponse(data); } } return new AbpJsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior, CamelCase = camelCase, Indented = indented };}
新聞熱點
疑難解答