Json formatting of the ABC getting started series, and the ABC getting started json

Source: Internet
Author: User

Json formatting of the ABC getting started series, and the ABC getting started json

After finishing the paging function, we are not eager to implement new functions in this section. To briefly introduce the use of Json In the Abp. In this section, why? Of course, it is paving the way. later articles often deal with Json.

I. What is Json?

JSON (Javascript Object Notation) is a lightweight data exchange format. Easy to read and write. It is also easy to parse and generate machines. JSON uses a completely language-independent text format, but it also uses a habit similar to the C language family (including C, C ++, C #, Java, Javascript, Perl, Python, and so on ). These features make JSON an ideal data exchange language.

Json is generally used to represent:

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

Ii. JsonResult in Asp.net Mvc

In Asp.net mvc, JsonResult is provided by default to handle situations where data in Json format needs to be returned.

Generally, we can use the following methods:

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 () is the virtual method provided in the Controller base class.

The returned json result is formatted as follows:

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

Observe the returned json results carefully:

The returned fields are in the same case as those in the code. This requires that we also use the same case (item. Title, item. Genre, item. ReleaseDate) value in the front end as in the code ).

No success or failure information is included: if we want to determine whether the request is successful, we need to manually obtain the length of the json data packet.

The returned date is not formatted. You must format the output on the front end.

3. encapsulation of Json In the Abp

Therefore, ABC encapsulates AbpJsonResult inherited from JsonResult, which mainly adds two attributes:

CamelCase: CamelCase (the default value is true, that is, the CamelCase format)

Indented: whether to indent (the default value is false, that is, it is not formatted)

In addition, AbpController reloads the Controller's Json () method, forces all returned Json format data to be of the AbpJsonResult type, and provides a 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 };}

Use Controler to inherit from AbpController in ABP, directly use return Json (), and format the returned Json results:

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

The result indicates the returned data in the code. The other key-value pairs are encapsulated by an ABC, including whether to authenticate, whether to succeed, the error message, and the target Url. Are these parameters sweet.

You can also specify parameters for json format output by calling return AbpJson.

After careful observation, we will find that the date format is still strange. 2017-01-23T00: 00: 00. One T is added. View the AbpJsonReult source code and find that JsonConvert. SerializeObject (obj, settings) in the Newtonsoft. Json serialization component is called for serialization.

View the Newtonsoft. Json official website. For date formatting output, you must specify the DateTimeFormat of IsoDateTimeConverter.

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

So how do we specify the DateTimeFormat in our Abp?

The AbpDateTimeConverter class is provided to inherit from IsoDateTimeConverter.

However, you can view the Json serialization extension classes integrated in the 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, if DateTimeFormat is not specified, we can only do it ourselves. For details about the code, refer to the fourth Method to Solve the json Date Format problem.

When an exception occurs, the following results are output in the Json format returned by the Abp:

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

What should I do if I do not need to encapsulate the json package with the abcip?

Simple. You only need to mark the [DontWrapResult] feature on the method. This feature is actually a quick way to tell you not to use AbpJsonResult to wrap me, you can see 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 the AbpResultFilter and AbpExceptionFilter filters, the corresponding filter is performed based on the WrapResultAttribute and DontWrapResultAttribute features.

Iv. Json date formatting

Method 1: frontend JS conversion:

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

The second method is to specify the time serialization time format of JsonFormatter in the WepApiModule (module) of Abp.

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

PS: This method is only valid for webapis.

Summary

This section describes the following issues:

Implementation of JsonResult in Asp.net.

Can be used to re-encapsulate the JsonResult and specify the size of the hump and whether to indent the result in Json format.

How to format and output DateTime objects.

The Web layer expands AbpJsonResult to specify the time format.

Front-end: Convert the Json Date to the Date type of js, and then format the output.

WebApi: Specify DateFormatString in Moduel.

The above is the Json formatting of the ABC entry series introduced by xiaobian. I hope it will be helpful to you. If you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.