Home Backend Development C#.Net Tutorial Introduction to the usage of Json formatting in the ABP introductory series

Introduction to the usage of Json formatting in the ABP introductory series

Mar 19, 2017 am 10:27 AM
json

,JSON(JavaScript Object Notation) is a lightweight data exchange format. This article focuses on introducing Json formatting in the ABP introductory series. Friends who need it can refer to

. After talking about the paging function, we are not in a hurry to implement new functions in this section. Let’s briefly introduce the usage of Json in Abp. Why do we talk about it in this section? Of course, this is to pave the way. The following series of articles will often deal with Json.

1. What does Json do?

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

Json is generally used to represent:

Name/value pair:

{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
Copy after login

Array:

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

II, JsonResult in Asp.net Mvc

Asp.net mvc provides JsonResult by default to handle situations where Json format data needs to be returned.

Generally we can use it like this:

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);
}
Copy after login

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)\/"
 }
]
Copy after login

Carefully observe the returned json result, there are the following shortcomings:

The returned field case is consistent with the code . This requires us to use the same case in the front end as in the code (item.Title, item.Genre, item.ReleaseDate).

Does not contain success or failure information: If we want to determine whether the request is successful, we have to manually obtain the length of the json data packet.

The returned date is not formatted and needs to be formatted and output on the front end.

3. Encapsulation of Json in Abp

So Abp encapsulates AbpJsonResultInherits from JsonResult, which mainly adds Two attributes:

CamelCase: size of camel case (default is true, that is, small camel case format)

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

And in AbpController Overloaded the Json() method of the Controller, forcing all returned Json format data to be of the AbpJsonResult type, and providing 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
 };
}
Copy after login

In ABP, use Controller to inherit from AbpController, use return Json() directly, and 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
}
Copy after login

The result is the data returned specified in the code. Several other key-value pairs are encapsulated by ABP, including authentication, success, error information, and target Url. Are these parameters very sweet?

You can also specify parameters for json formatted output by calling return AbpJson().

If you look carefully, you will find that the date format is still weird. 2017-01-23T00:00:00, one more T. Looking at the AbpJsonReult source code, we found that JsonConvert.SerializeObject(obj, settings); in the Newtonsoft.Json Serialization component is called for serialization.

Check the introduction of Newtonsoft.Json official website. For date formatting 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)
Copy after login

So how do we specify this DateTimeFormat in our Abp?

The AbpDateTimeConverter class provided in ABP inherits from IsoDateTimeConverter.

But look at the Json serialization extension class integrated 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);
 }
 }
Copy after login

Obviously DateTimeFormat is not specified, so we can only do it ourselves. For specific codes, please refer to 4 ways to solve json date format problems The fourth method of the method.

当有异常发生时,Abp返回的Json格式化输出以下结果:

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

当不需要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;
  }
 }
}
Copy after login

在AbpResultFilter和AbpExceptionFilter过滤器中会根据WrapResultAttribute、DontWrapResultAttribute特性进行相应的过滤。

四、Json日期格式化

第一种办法:前端JS转换:

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

第二种办法:在Abp的WepApiModule(模块)中指定JsonFormatter的时间序列化时间格式。

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

PS:这种方法仅对WebApi有效。

总结

本节主要讲解了以下几个问题:

Asp.net中JsonResult的实现。

ABP对JsonResult的再封装,支持指定大小驼峰及是否缩进进行Json格式化。

如何对DateTime类型对象进行格式化输出。

Web层通过拓展AbpJsonResult,指定时间格式。

前端,通过将Json日期转换为js的Date类型,再格式化输出。

WebApi,通过在Moduel中指定DateFormatString。

The above is the detailed content of Introduction to the usage of Json formatting in the ABP introductory series. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

How to exclude a field from JSON using @Expose annotation in Java? How to exclude a field from JSON using @Expose annotation in Java? Sep 16, 2023 pm 09:49 PM

The Gson@Expose annotation can be used to mark whether a field is exposed (contained or not) for serialization or deserialization. The @Expose annotation can take two parameters, each parameter is a boolean value and can take the value true or false. In order for GSON to react to the @Expose annotation, we have to create a Gson instance using the GsonBuilder class and need to call the excludeFieldsWithoutExposeAnnotation() method, which configures Gson to exclude all fields without Expose annotation from serialization or deserialization. Syntax publicGsonBuilderexclud

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Nov 18, 2023 pm 01:59 PM

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. When writing programs in Golang, we often need to convert the structure into a JSON string. In this process, the json.MarshalIndent function can help us. Implement formatted output. Below we will explain in detail how to use this function and provide specific code examples. First, let's create a structure containing some data. The following is an indication

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Use PHP's json_encode() function to convert an array or object into a JSON string and format the output Use PHP's json_encode() function to convert an array or object into a JSON string and format the output Nov 03, 2023 pm 03:44 PM

Using PHP's json_encode() function to convert an array or object into a JSON string and format the output can make it easier to transfer and exchange data between different platforms and languages. This article will introduce the basic usage of the json_encode() function and how to format and output a JSON string. 1. Basic usage of json_encode() function The basic syntax of json_encode() function is as follows: stringjson_encod

See all articles