Four Solutions to the Json Date Format problem (ultra-detailed): json Date Format

Source: Internet
Author: User
Tags iso 8601 iso 8601 date iso 8601 date format

Four Solutions to the Json Date Format problem (ultra-detailed): json Date Format

During development, sometimes data in json format needs to be returned from the server. If the DateTime type data in the background code is serialized using the tool class provided by the system, a long number will be obtained to represent the date data, as follows:

// Set the server response result to context in plain text format. response. contentType = "text/plain"; // List of Student objects <Student> students = new List <Student> {new Student () {Name = "Tom", Birthday = Convert. toDateTime ("12:12:12")}, new Student () {Name = "Rose", Birthday = Convert. toDateTime ("11:12:12")}, new Student () {Name = "Mark", Birthday = Convert. toDateTime ("10:12:12") }}; // javascript serializer JavascriptSerializer jss = new JavascriptSerializer (); // serialize the student collection object to get the json character string studentsJson = jss. serialize (students); // returns the string to the client context. response. write (studentsJson); context. response. end ();

The running result is:

Among them, Tom's birthday "January 1, 1970" has changed to 1391141532000, which is actually the number of milliseconds since 1391141532000/1000; 60/60/24/365/44.11 = 1970 years, 44 + =, in this way, we can obtain the year, month, day, hour, minute, second, and millisecond. This format is a feasible representation, but not a friendly one that ordinary people can understand. How can this format be changed?

Solution:

Method 1: on the server side, convert the date format using the Select method or LINQ expression and send it to the client:

Using System; using System. collections. generic; using System. web; using System. web. script. serialization; namespace JsonDate1 {using System. linq; /// <summary> /// student class, test Purpose // </summary> public class Student {// <summary> // Name // </summary> public String Name {get; set ;} /// <summary> /// Birthday /// </summary> public DateTime Birthday {get; set ;}} /// <summary> /// return the json character of the student set /// </summary> public class GetJson: IHttpHandler {public void ProcessRequest (HttpContext context) {// set the server response result to context in plain text format. response. contentType = "text/plain"; // List of Student objects <Student> students = new List <Student> {new Student () {Name = "Tom", Birthday = Convert. toDateTime ("12:12:12")}, new Student () {Name = "Rose", Birthday = Convert. toDateTime ("11:12:12")}, new Student () {Name = "Mark", Birthday = Convert. toDateTime ("10:12:12") }}; // use the Select method to re-project the object set and convert the Birthday attribute to a new one. // remember to rename the attributes after they change, and immediately execute var studentSet = students. select (p => new {p. name, Birthday = p. birthday. toString ("yyyy-mm-dd ")}). toList (); // javascript serializer JavascriptSerializer jss = new JavascriptSerializer (); // serialize the student collection object to obtain the json character string studentsJson = jss. serialize (studentSet); // returns the string to the client context. response. write (studentsJson); context. response. end () ;}public bool IsReusable {get {return false ;}}}}

The Select method re-projects the object set to convert the Birthday attribute into a new attribute. Note that the attribute must be renamed after the attribute changes. The attribute names can be the same; here, you can use the select method or the LINQ query expression, or you can select another method to achieve the same purpose. This method can remove the attributes not used by the client in the collection, to achieve simple performance optimization.

Running result:

At this time, the date format has changed to a friendly format, but in javascript this is only a string.

Method 2:

In javascript, convert the string in "Birthday": "\/Date (1391141532000) \/" to a Date object in javascript, you can delete the non-numeric characters in the Value corresponding to the Key Birthday in the form of replacement, To a number 1391141532000, and then instantiate a Date object, 1391141532000 milliseconds as the parameter, get a date object in javascript, the Code is as follows:

<! DOCTYPE html> 

Running result:

Use regular/\ D/igm on to replace all non-numeric values. \ D indicates non-numeric values, while igm indicates parameters, indicating case-insensitive values, respectively; multiple times, global replacement, and multi-line replacement. In some cases, more than 86 occurs. You only need to change the regular expression to achieve the same purpose. In addition, if this problem occurs repeatedly in the project, you can extend the javascript method by using the following code:

$ (Function () {$. getJSON ("getJson. ashx ", function (students) {$. each (students, function (index, obj) {$ ("<li/>" example .html (obj. name ). appendTo ("# ulStudents"); // use a regular expression to set non-numbers (\ D) in the birthday attribute) delete // and convert the number of milliseconds to the numeric type var birthdayMilliseconds = parseInt (obj. birthday. replace (// \ D/igm, ""); // instantiate a new Date format, using the parameter var birthday = new Date (birthdayMilliseconds) in milliseconds since January 1, January 1, 1970 ); $ ("<li/>" birthday .html (birthday. toLocaleString ()). appendTo ("# ulStudents"); $ ("<li/>" example .html (obj. birthday. toDate ()). appendTo ("# ulStudents") ;}); // extend the toDate Method to the String object. You can complete the String method as required. prototype. toDate = function () {var dateMilliseconds; if (isNaN (this) {// use a regular expression to delete dateMilliseconds = this from a non-number (\ D) in the date attribute. replace (/\ D/igm, "");} else {dateMilliseconds = this;} // instantiate a new date format, return new Date (parseInt (dateMilliseconds ));};

The above extended toDate method is not necessarily reasonable and is not powerful enough. You can modify it as needed.

Method 3:

You can select some third-party json tool classes, some of which have already been processed for date format issues. Common json serialization and deserialization tool libraries include:

1. fastJSON.
2. JSON_checker.
3. Jayrock.
4. Json. NET-LINQ to JSON.
5. LitJSON.
6. JSON for. NET.
7. JsonFx.
8. JSONSharp.
9. JsonExSerializer.
10. fluent-json
11. Manatee Json

Here we use litjson as the serialization and deserialization json tool class as an example. The Code is as follows:

Using System; using System. collections. generic; using System. web; using LitJson; namespace JsonDate2 {using System. linq; /// <summary> /// student class, test Purpose // </summary> public class Student {// <summary> // Name // </summary> public String Name {get; set ;} /// <summary> /// Birthday /// </summary> public DateTime Birthday {get; set ;}} /// <summary> /// return the json character of the student set /// </summary> public class GetJson: IHttpHandler {public void ProcessRequest (HttpContext context) {// set the server response result to context in plain text format. response. contentType = "text/plain"; // List of Student objects <Student> students = new List <Student> {new Student () {Name = "Tom", Birthday = Convert. toDateTime ("12:12:12")}, new Student () {Name = "Rose", Birthday = Convert. toDateTime ("11:12:12")}, new Student () {Name = "Mark", Birthday = Convert. toDateTime ("10:12:12") }}; // serialize the student collection object to obtain the json character string studentsJson = JsonMapper. toJson (students); // returns the string to the client context. response. write (studentsJson); context. response. end () ;}public bool IsReusable {get {return false ;}}}}

The running result is as follows:

At this time, the date format is basically correct, as long as the date is directly instantiated in javascript,

var date = new Date("01/31/2014 12:12:12");alert(date.toLocaleString());

The client code is as follows:

$(function () { $.getJSON("GetJson2.ashx", function (students) { $.each(students, function (index, obj) { $("<li/>").html(obj.Name).appendTo("#ulStudents"); var birthday = new Date(obj.Birthday); $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents"); }); }); }); var date = new Date("01/31/2014 12:12:12"); alert(date.toLocaleString());

Method 4:

This text was sent to the blog and some netizens raised their valuable comments. I did not consider the situation in MVC. In fact, handler can also be used in MVC, so the difference is not great, however, MVC has an Action that specifically responds to the server as JSON. The Code is as follows:

Using System; using System. web. mvc; namespace JSONDateMVC. controllers {public class HomeController: Controller {public JsonResult GetJson1 () {// serialize the current date and time object, and allow the client to Get request return Json (DateTime. now, JsonRequestBehavior. allowGet );}}}

Running result:

Download an Application/json file named GetJson1 with the content "\/Date (1391418272884 )\/"

From the above situation, the date format is not specially processed during serialization in MVC. We can decompile the source code:

Return:

Protected internal JsonResult Json (object data, JsonRequestBehavior behavior) {return this. json (data, null, null, behavior);} this. json method protected internal virtual JsonResult Json (object data, string contentType, Encoding contentEncoding, describehavior) {return new JsonResult {Data = data, ContentType = contentType, ContentEncoding = contentEncoding, jsonRequestBehavior = behavior };}

A subclass of the ActionResult class of the JsonResult class. The ExecuteResult method is as follows:

From the code above, it is not difficult to see that Microsoft's JsonResult class still uses JavascriptSerializer, so the returned results are the same as those of method 1 when it is not processed, to solve this problem, we can derive a new class, rewrite the ExecuteResult method, and use Json.net to complete serialization, JsonResultPro. the code for the cs file is as follows:

Namespace JSONDateMVC. common {using System; using System. web; using System. web. mvc; using Newtonsoft. json; using Newtonsoft. json. converters; public class JsonResultPro: JsonResult {public JsonResultPro () {} public JsonResultPro (object data, JsonRequestBehavior behavior) {base. data = data; base. jsonRequestBehavior = behavior; this. dateTimeFormat = "yyyy-MM-dd hh: mm: ss";} public JsonResultPro (obje Ct data, String dateTimeFormat) {base. data = data; base. jsonRequestBehavior = JsonRequestBehavior. allowGet; this. dateTimeFormat = dateTimeFormat;} // <summary> // Date Format // </summary> public string DateTimeFormat {get; set;} public override void ExecuteResult (ControllerContext context) {if (context = null) {throw new ArgumentNullException ("context");} if (this. jsonRequestBehavior = JsonR EquestBehavior. denyGet) & string. equals (context. httpContext. request. httpMethod, "GET", StringComparison. ordinalIgnoreCase) {throw new InvalidOperationException ("MvcResources. jsonRequest_GetNotAllowed ");} HttpResponseBase base2 = context. httpContext. response; if (! String. IsNullOrEmpty (this. ContentType) {base2.ContentType = this. ContentType;} else {base2.ContentType = "application/json";} if (this. ContentEncoding! = Null) {base2.ContentEncoding = this. ContentEncoding;} if (this. Data! = Null) {// convert System. dateTime to ISO 8601 Date Format // ISO 8601 (for example, 2008-04-12T12: 53Z) IsoDateTimeConverter isoDateTimeConverter = new IsoDateTimeConverter (); // set the date format isoDateTimeConverter. dateTimeFormat = DateTimeFormat; // serialized String jsonResult = JsonConvert. serializeObject (this. data, isoDateTimeConverter); // base2.Write (jsonResult );}}}}

The above JsonResultPro Action type code is as follows:

Public JsonResultPro GetJson2 () {// serialize the current date and time object, and allow the client to Get requests. Note that H is capital return new JsonResultPro (DateTime. now, "yyyy-MM-dd HH: mm ");}

Running result:

"

In this way, you can set the date Format according to your own meaning, but note that the date Format, such as the regular Format, is different, for example, H indicates the time in uppercase and 12 hours in lowercase. There are also several questions to ask:

1. There are many changes in the Code obtained through Reflector decompilation. For example, the attribute will change to the form of the get_Request () method. I wonder if you have any better method.

2. The resource file MvcResources. JsonRequest_GetNotAllowed is used in the decompiled code. How can it be used during rewriting?

The above is a summary of the four solutions to the Json Date Format problem introduced by the small Editor (ultra-detailed). I hope it will help you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. 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.