Jason formatting of ABP introduction series

Time:2021-12-29

After talking about the paging function, we don’t need to implement the new function in this section. Let’s briefly introduce the usage of JSON in ABP. Why in this section? Of course, it’s paving the way. The later series of articles will often deal with Jason.

1、 What does Jason do

JSON (JavaScript object notation) is a lightweight data exchange format. Easy to read and write. It is also easy to machine parse and generate. JSON adopts a text format completely independent of the language, but it also uses habits similar to the C language family (including C, C + +, c#, Java, JavaScript, Perl, python, etc.). These features make JSON an ideal data exchange language.

JSON is generally used to indicate:

Name / value pair:


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

Array:


{ "people":[
  {"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
  {"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
  {"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
 ]
}

2、 ASP Jsonresult in. Net MVC

Asp. Net MVC provides jsonresult by default to handle the case where data in JSON format needs to be returned.

Generally, we can use it as follows:


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);
}

Where JSON () is the virtual method provided in the controller base class.

The returned JSON result is formatted as:


[
 {
 "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)\/"
 }
]

Carefully observe the returned JSON results. There are the following deficiencies:

The case of the returned field is consistent with that in the code. This requires that we also use the same case in the front end as in the code (item. Title, item. Genre, item. Releasedate).

It does not contain success or failure information: if we want to judge whether the request is successful, we need to manually obtain it by obtaining the length of the JSON packet.

The returned date is unformatted. You need to format the output at the front end.

3、 Encapsulation of JSON in ABP

Therefore, ABP encapsulates abpjsonresult, which inherits from jsonresult, and mainly adds two attributes:

CamelCase: large and small humps (the default is true, i.e. small hump format)

Indented: whether to indent (the default is false, i.e. unformatted)

The controller’s JSON () method is overloaded in abpcontroller, forcing all returned JSON format data to be of abpjsonresult type, and providing the virtual method of 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
 };
}

In ABP, use controller to inherit from abpcontroller, and directly use return json() to format the returned JSON result:


{
 "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
}

Where result is the returned data specified in the code. Several other key value pairs are encapsulated by ABP, including authentication, success, error information, and target URL. These parameters are not very sweet.

You can also call return abpjson() to specify parameters for JSON formatted output.

If you look closely, you will find that the date format is still strange. 2017-01-23t00:00:00, one more t. Check the source code of abpjsonreult and find that it calls newtonsoft Jsonconvert. In the JSON serialization component SerializeObject(obj, settings); Serialize.

View newtonsoft According to the official website of Jason, for date formatted output, you need to specify the datetimeformat of isodatetimeconverter.


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

How do we specify this datetimeformat in our ABP?

Abpdatetimeconverter class is provided in ABP, which inherits from isodatetimeconverter.

But check the integrated JSON serialization extension class in ABP:


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);
 }
 }

Obviously, datetimeformat is not specified, so we can only do it ourselves. Please refer to the specific codeThe fourth way to solve the problem of JSON date format

When an exception occurs, the JSON format returned by ABP outputs the following results:


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

What happens when you don’t need ABP to encapsulate JSON?

Simple. Just mark the [dontwrapresult] attribute on the method. This feature is actually a shortcut to tell ABP not to wrap me with abpjsonresult. Just look at the source code:


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;
  }
 }
}

In abperesultfilter and abpexceptionfilter, corresponding filtering will be carried out according to the wrapsesultattribute and dontwrapresultattribute attributes.

4、 JSON date formatting

The first method: front-end JS conversion:

//Format display JSON date format
 function showDate(jsonDate) {
  var date = new Date(jsonDate);
  var formatDate = date.toDateString();
  return formatDate;
 }

The second method: specify the time serialization time format of jsonformatter in wepapimodule of ABP.


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

PS: this method is only valid for webapi.

summary

This section mainly explains the following issues:

Asp. Net.

ABP repackages jsonresult, and supports specified hump size and whether to indent for JSON formatting.

How to format and output datetime type objects.

The web layer specifies the time format by expanding abpjsonresult.

The front end converts the JSON date to the JS date type, and then formats the output.

Webapi, by specifying dateformatstring in moduel.

The above is the Jason format of ABP introductory series introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support to the developeppaer website!