, JSON (JavaScript Object Notation) is a lightweight data interchange format. This article focuses on the introduction of the ABP series of JSON format, the need for friends can refer to the following
Finish the paging function, this section we don't hurry to implement the new features. To briefly describe the use of JSON in the ABP. Why do you want to talk about it in this section? Of course is to do the groundwork Ah, the following series of articles will often and JSON this thing to deal with.
I. What does JSON do?
JSON (Javascript Object Notation) is a lightweight data interchange format. Easy for people to read and write. It is also easy for machine parsing and generation. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, Javascript, Perl, Python, etc.). These features make JSON an ideal data exchange language.
JSON is typically used to represent:
Name/value pairs:
{"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.
Jsonresult is provided by default in ASP. NET MVC to handle situations where JSON-formatted data needs to be returned.
In general we can use 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);
}
where JSON () is the virtual method provided in the Controller base class.
The returned JSON results are 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)\/"
}
]
Looking closely at the JSON results returned, there are a few disadvantages:
The returned fields are case-consistent with the code. This requires that we also take the value (item) in the front-end with a consistent case in the code. Title,item. Genre,item. ReleaseDate).
Does not contain success failure information: If we want to determine whether the request is successful, we will manually obtain the length of the JSON packet.
The returned date is unformatted, and you need to format the output yourself at the front end.
Third, the encapsulation of JSON in ABP
So the ABP encapsulates the Abpjsonresult inherited from Jsonresult, which mainly adds two properties:
CamelCase: Size Hump (default is true, i.e. small hump format)
Indented: whether to indent (false by default, that is, unformatted)
The controller's JSON () method is overloaded in Abpcontroller, forcing all returned JSON-formatted data to be of type Abpjsonresult 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
};
}
Using Controler in the ABP to inherit from Abpcontroller, use return JSON directly () to return the JSON result after formatting:
{
"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 specifies the data returned in the code. Several other key-value pairs are ABP-encapsulated, containing authentication, success, error messages, and destination URLs. These few parameters are not very sweet.
You can also specify the parameters for JSON formatted output by calling return Abpjson ().
Careful observation will find that the date format is still weird. 2017-01-23t00:00:00, one more T. View Abpjsonreult source Discovery invokes the Jsonconvert.serializeobject (obj, settings) in the Newtonsoft.json serialization component, which is serialized.
View Newtonsoft.json Official website Introduction, date format output, you need to specify Isodatetimeconverter DateTimeFormat.
IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
JsonConvert.SerializeObject(dt, Formatting.Indented, timeFormat)
So how do we specify this DateTimeFormat in our ABP?
The Abpdatetimeconverter class inherited from Isodatetimeconverter is provided in the ABP.
But look at the JSON serialization extension classes that are 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 did not specify DateTimeFormat, then we can only do it ourselves, the specific code please refer to the 4 ways to solve the JSON date format problem fourth method.
When an exception occurs, the JSON format returned by the ABP outputs the following results:
{
"targetUrl": null,
"result": null,
"success": false,
"error": {
"message": "An internal error occured during your request!",
"details": "..."
},
"unAuthorizedRequest": false
}
What if I don't need the ABP to encapsulate the JSON package?
Simple. You only need to mark the [Dontwrapresult] attribute on the method. This feature is actually a shortcut used to tell ABP not to use Abpjsonresult package me, see the source code to understand:
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;
}
}
}
The Abpresultfilter and Abpexceptionfilter filters are filtered according to the Wrapresultattribute and dontwrapresultattribute characteristics.
Iv. JSON date formatting
The first approach: front-end JS conversion:
/ / Formatted display json date format
Function showDate(jsonDate) {
Var date = new Date(jsonDate);
Var formatDate = date.toDateString();
Return formatDate;
}
The second approach: Specify the time-serialized time format for Jsonformatter in the Wepapimodule (module) of the ABP.
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "Yyyy-mm-dd HH: Mm:ss ";
PS: This method is only valid for Webapi.
Summarize
This section focuses on the following issues:
Implementation of Jsonresult in ASP.
ABP's re-encapsulation of the Jsonresult supports specifying the size of the hump and whether it is indented for JSON formatting.
How to format the output of a DateTime type object.
The Web layer specifies the time format by extending the Abpjsonresult.
The front end, by converting the JSON date to the date type of JS, and then formatting the output.
WEBAPI, by specifying the dateformatstring in the Moduel.