欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ABP入門系列之Json格式化

 更新時間:2017年03月16日 09:35:51   投稿:mrr  
,JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。本文重點給大家介紹ABP入門系列之Json格式化,需要的朋友可以參考下

講完了分頁功能,這一節(jié)我們先不急著實現(xiàn)新的功能。來簡要介紹下Abp中Json的用法。為什么要在這一節(jié)講呢?當然是做鋪墊啊,后面的系列文章會經(jīng)常和Json這個東西打交道。

一、Json是干什么的

JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。 易于人閱讀和編寫。同時也易于機器解析和生成。JSON采用完全獨立于語言的文本格式,但是也使用了類似于C語言家族的習(xí)慣(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 這些特性使JSON成為理想的數(shù)據(jù)交換語言。

Json一般用于表示:

名稱/值對:

{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}

數(shù)組:

{ "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格式數(shù)據(jù)的情況。

一般我們可以這樣使用:

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結(jié)果格式化后為:

[
 {
 "Title": "Ghostbusters",
 "Genre": "Comedy",
 "ReleaseDate": "\/Date(1483200000000)\/"
 },
 {
 "Title": "Gone with Wind",
 "Genre": "Drama",
 "ReleaseDate": "\/Date(1483372800000)\/"
 },
 {
 "Title": "Star Wars",
 "Genre": "Science Fiction",
 "ReleaseDate": "\/Date(1485100800000)\/"
 }
]

仔細觀察返回的json結(jié)果,有以下幾點不足:

返回的字段大小寫與代碼中一致。這就要求我們在前端中也要與代碼中用一致的大小寫進行取值(item.Title,item.Genre,item.ReleaseDate)。

不包含成功失敗信息:如果我們要判斷請求是否成功,我們要手動通過獲取json數(shù)據(jù)包的length獲取。

返回的日期未格式化,在前端還需自行格式化輸出。

三、Abp中對Json的封裝

所以Abp封裝了AbpJsonResult繼承于JsonResult,其中主要添加了兩個屬性:

CamelCase:大小駝峰(默認為true,即小駝峰格式)

Indented :是否縮進(默認為false,即未格式化)

并在AbpController中重載了Controller的Json()方法,強制所有返回的Json格式數(shù)據(jù)為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
 };
}

在ABP中用Controler繼承自AbpController,直接使用return Json(),將返回Json結(jié)果格式化后:

{
 "result": [
 {
  "title": "Ghostbusters",
  "genre": "Comedy",
  "releaseDate": "2017-01-01T00:00:00"
 },
 {
  "title": "Gone with Wind",
  "genre": "Drama",
  "releaseDate": "2017-01-03T00:00:00"
 },
 {
  "title": "Star Wars",
  "genre": "Science Fiction",
  "releaseDate": "2017-01-23T00:00:00"
 }
 ],
 "targetUrl": null,
 "success": true,
 "error": null,
 "unAuthorizedRequest": false,
 "__abp": true
}

其中result為代碼中指定返回的數(shù)據(jù)。其他幾個鍵值對是ABP封裝的,包含了是否認證、是否成功、錯誤信息,以及目標Url。這幾個參數(shù)是不是很sweet。

也可以通過調(diào)用return AbpJson()來指定參數(shù)進行json格式化輸出。

仔細觀察會發(fā)現(xiàn)日期格式還是怪怪的。2017-01-23T00:00:00,多了一個T。查看AbpJsonReult源碼發(fā)現(xiàn)調(diào)用的是Newtonsoft.Json序列化組件中的JsonConvert.SerializeObject(obj, settings);進行序列化。

查看Newtonsoft.Json官網(wǎng)介紹,日期格式化輸出,需要指定IsoDateTimeConverter的DateTimeFormat即可。

IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
   timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
JsonConvert.SerializeObject(dt, Formatting.Indented, timeFormat)

那在我們Abp中我們怎么去指定這個DateTimeFormat呢?

ABP中提供了AbpDateTimeConverter類繼承自IsoDateTimeConverter。

但查看ABP中集成的Json序列化擴展類:

public static class JsonExtensions
 {
 /// <summary>Converts given object to JSON string.</summary>
 /// <returns></returns>
 public static string ToJsonString(this object obj, bool camelCase = false, bool indented = false)
 {
  JsonSerializerSettings settings = new JsonSerializerSettings();
  if (camelCase)
  settings.ContractResolver = (IContractResolver) new CamelCasePropertyNamesContractResolver();
  if (indented)
  settings.Formatting = Formatting.Indented;
  settings.Converters.Insert(0, (JsonConverter) new AbpDateTimeConverter());
  return JsonConvert.SerializeObject(obj, settings);
 }
 }

明顯沒有指定DateTimeFormat,那我們就只能自己動手了,具體代碼請參考4種解決json日期格式問題的辦法的第四種辦法

當有異常發(fā)生時,Abp返回的Json格式化輸出以下結(jié)果:

{
 "targetUrl": null,
 "result": null,
 "success": false,
 "error": {
 "message": "An internal error occured during your request!",
 "details": "..."
 },
 "unAuthorizedRequest": false
}

當不需要abp對json進行封裝包裹怎么辦?

簡單。只需要在方法上標記[DontWrapResult]特性即可。這個特性其實是一個快捷方式用來告訴ABP不要用AbpJsonResult包裹我,看源碼就明白了:

namespace Abp.Web.Models
{
 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method)]
 public class DontWrapResultAttribute : WrapResultAttribute
 {
  /// <summary>
  /// Initializes a new instance of the <see cref="DontWrapResultAttribute"/> class.
  /// </summary>
  public DontWrapResultAttribute()
   : base(false, false)
  {
  }
 }
 /// <summary>
 /// Used to determine how ABP should wrap response on the web layer.
 /// </summary>
 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method)]
 public class WrapResultAttribute : Attribute
 {
  /// <summary>
  /// Wrap result on success.
  /// </summary>
  public bool WrapOnSuccess { get; set; }
  /// <summary>
  /// Wrap result on error.
  /// </summary>
  public bool WrapOnError { get; set; }
  /// <summary>
  /// Log errors.
  /// Default: true.
  /// </summary>
  public bool LogError { get; set; }
  /// <summary>
  /// Initializes a new instance of the <see cref="WrapResultAttribute"/> class.
  /// </summary>
  /// <param name="wrapOnSuccess">Wrap result on success.</param>
  /// <param name="wrapOnError">Wrap result on error.</param>
  public WrapResultAttribute(bool wrapOnSuccess = true, bool wrapOnError = true)
  {
   WrapOnSuccess = wrapOnSuccess;
   WrapOnError = wrapOnError;
   LogError = true;
  }
 }
}

在AbpResultFilter和AbpExceptionFilter過濾器中會根據(jù)WrapResultAttribute、DontWrapResultAttribute特性進行相應(yīng)的過濾。

四、Json日期格式化

第一種辦法:前端JS轉(zhuǎn)換:

 //格式化顯示json日期格式
 function showDate(jsonDate) {
  var date = new Date(jsonDate);
  var formatDate = date.toDateString();
  return formatDate;
 }

第二種辦法:在Abp的WepApiModule(模塊)中指定JsonFormatter的時間序列化時間格式。

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateFormatString ="yyyy-MM-dd HH:mm:ss";

PS:這種方法僅對WebApi有效。

總結(jié)

本節(jié)主要講解了以下幾個問題:

Asp.net中JsonResult的實現(xiàn)。

ABP對JsonResult的再封裝,支持指定大小駝峰及是否縮進進行Json格式化。

如何對DateTime類型對象進行格式化輸出。

Web層通過拓展AbpJsonResult,指定時間格式。

前端,通過將Json日期轉(zhuǎn)換為js的Date類型,再格式化輸出。

WebApi,通過在Moduel中指定DateFormatString。

以上所述是小編給大家介紹的ABP入門系列之Json格式化,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • 19個必須知道的Visual Studio快捷鍵

    19個必須知道的Visual Studio快捷鍵

    這篇文章主要為大家詳細介紹了19個必須知道的Visual Studio快捷鍵,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-12-12
  • http轉(zhuǎn)https的實戰(zhàn)記錄(iis 7.5)

    http轉(zhuǎn)https的實戰(zhàn)記錄(iis 7.5)

    這篇文章主要給大家介紹了關(guān)于http轉(zhuǎn)https的相關(guān)資料,文中是最近的一次實戰(zhàn)記錄,基于iis7.5,通過一步步的圖文介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。
    2018-01-01
  • ASP.NET中Ajax怎么使用

    ASP.NET中Ajax怎么使用

    這篇文章主要介紹了ASP.NET中Ajax使用方法的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-07-07
  • c# 讀取文件內(nèi)容存放到int數(shù)組 array.txt

    c# 讀取文件內(nèi)容存放到int數(shù)組 array.txt

    c# 讀取文本的內(nèi)容,并且將內(nèi)容保存到int數(shù)組中,大家可以學(xué)習(xí)到c#一些數(shù)組跟讀取內(nèi)容的函數(shù)。
    2009-04-04
  • 詳解ASP.NET Core MVC 源碼學(xué)習(xí):Routing 路由

    詳解ASP.NET Core MVC 源碼學(xué)習(xí):Routing 路由

    本篇文章主要介紹了詳解ASP.NET Core MVC 源碼學(xué)習(xí):Routing 路由 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-03-03
  • C# ToString格式大全

    C# ToString格式大全

    需要將其它類型的變量,轉(zhuǎn)換為字符串類型的一些常見方法與屬性。
    2008-12-12
  • C#中的FileUpload 選擇后的預(yù)覽效果具體實現(xiàn)

    C#中的FileUpload 選擇后的預(yù)覽效果具體實現(xiàn)

    選擇后的預(yù)覽效果實現(xiàn)的方法有很多,在本文為大家介紹下使用C#中的FileUpload是如何實現(xiàn)的,感興趣的朋友不要錯過
    2013-12-12
  • 使用本機IIS?Express開發(fā)Asp.Net?Core應(yīng)用圖文教程

    使用本機IIS?Express開發(fā)Asp.Net?Core應(yīng)用圖文教程

    IIS Express是一個Mini版的IIS,能夠支持所有的Web開發(fā)任務(wù),本篇經(jīng)驗將和大家介紹使用自定義主機名來訪問運行在IIS?Express上的站點程序的方法,希望對大家的工作和學(xué)習(xí)有所幫助
    2023-06-06
  • Asp.Net修改上傳文件大小限制方法

    Asp.Net修改上傳文件大小限制方法

    本文主要分享了Asp.Net修改上傳文件大小限制的方法--修改web.config,需要的朋友可以看下
    2016-12-12
  • C#中使用SQLite數(shù)據(jù)庫的方法介紹

    C#中使用SQLite數(shù)據(jù)庫的方法介紹

    SQLite是一個開源的輕量級的桌面型數(shù)據(jù)庫,它將幾乎所有數(shù)據(jù)庫要素(包括定義、表、索引和數(shù)據(jù)本身)都保存在一個單一的文件中。SQLite用C編寫實現(xiàn),它在內(nèi)存消耗、文件體積、操作性能、簡單性方面都有不錯的表現(xiàn)
    2012-01-01

最新評論