Solving Date and camelCasing problem of JSON in ASP.NET MVC

Sheonarayan
Posted by in ASP.NET MVC category on for Intermediate level | Points: 250 | Views : 4216 red flag
Rating: 5 out of 5  
 2 vote(s)

This articles explains how to solve the Date format and camelCasing issue of JSON format in ASP.NET MVC. We will also learn how to create and use a custom ActionResult in ASP.NET MVC.
Recommendation
Read Simple controller dependency injection in ASP.NET MVC before this article.

Introduction

Returning JSON data containing Date field from ASP.NET MVC action method return type as JsonResult gives very messy date data something like 

{"AutoId":16,"FirstName":"Sheo","LastName":"Narayan","Age":50,"Active":true,"BirthDate":"\/Date(1450059758965)\/"}
Notice the bold words in the above code snippet. This date data is neither readable properly or understandable correctly. To solve this issue, we can find different approaches.

Solving JSON Date format problem

There are several solutions to above mentioned problem.

Approach 1 - using Newtonsoft.Json converter

The 1st and easiest solution to this problem is to use Newtonsoft.Json converter. Newtonsoft.Json gets added by default when we create a new ASP.NET MVC project in Visual Studio. So we just need to use that namespace. In case Newtonsoft is not available int he project, we can easily add it using Manage NuGet packages.

public JsonResult OutputToJson()
{
      PersonalDetail model = new PersonalDetail()
      {
           Active = true,
           Age = 50,
           AutoId = 16,
           BirthDate = DateTime.Now,
           FirstName = "Sheo",
           LastName = "Narayan"
       };

  return Json(Newtonsoft.Json.JsonConvert.SerializeObject(model), JsonRequestBehavior.AllowGet);
   // collection of objects can also be used
}

SerializeObject method of the JsonConvert of Newtonsoft converts the date to readable and understandable format and now it looks like below

"{\"AutoId\":16,\"FirstName\":\"Sheo\",\"LastName\":\"Narayan\",\"Age\":50,\"Active\":true,\"BirthDate\":\"2015-12-14T07:57:38.7027951+05:30\"}"
The Date and Time is separated by "T" character in the BirthDate field. Even if this has solved the problem a bit but still it is not great. So then we can follow the 2nd approach of creating our own JSON return type from the controller action method.

IMPORTANT: You may notice that your loop of iterating through JSON object at client side may not work in case you are using a collection of objects into SerializeObject method. So simply use as shown below and your iteration code works.

var jsonData = JSON.parse(serializedJsonData);

Approach 2 - Creating custom Json return type to customize date format

In this approach, we can customize the date format we want to return as JSON string for all Date type of fields in the collection.

To do this, we need to create a custom action result return type and here is the way to do it. 
Creating custom return type
Create a class and inherit it with JsonResult class as we have to return Json data. JsonResult class has overridable ExecuteResult method that we will override and write our own functionality.

namespace MVCTraining5.Utility
{
    public class MyJSONResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            string dateFormat = "dd-MM-yyyy HH:mm:ss"; // change the format here

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "application/json";
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            if (Data != null)
            {
                // Use Newtonsoft converter
                var isoDTConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
                isoDTConvert.DateTimeFormat = dateFormat;
                response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(Data, isoDTConvert));
            }
        }
    }
}
In above code snippet, we are first creating a string variable named dateFormat with the format in which we want the date field to appear. In last if condition we are checking if Data property is set to this class then use the IsoDateTimeConverter (that is using date format given in the dateFormat variable) while serializing the data into Json format and the same is bring returned to the response.
Using custom Json return type
After creating the above return type, we can use it in our Action method of the controller like this. Notice the return type and return statement in below code snippet that is in bold.

        public Utility.MyJSONResult OutputToJsonWithCorrectDate()
        {
            PersonalDetail model = new PersonalDetail()
            {
                Active = true,
                Age = 50,
                AutoId = 16,
                BirthDate = DateTime.Now,
                FirstName = "Sheo",
                LastName = "Narayan"
            };

            return new Utility.MyJSONResult()
            {
                Data = model,
            };
        }
We will change our return type to the type we created above and while returning we will use the instance of the MyJsonResult and set its  Data property. This will give JSON output like this

{"AutoId":16,"FirstName":"Sheo","LastName":"Narayan","Age":50,"Active":true,"BirthDate":"14-12-2015 08:03:44"}
Notice that now, date format is easily readable and understandable, currently it is coming in dd-MM-yyyy format, if we want to change it to MM-dd-yyyy or any other format, we just need to change the dateFormat variable in the custom return type declaration ExecuteResult method.

Converting JSON property to camelCase

In many scenarios, we might need to convert the JSON data properties name to camelCase, to do that we can follow below approach.

public JsonResult OutputToJson()
{
   PersonalDetail model = new PersonalDetail()
   {
         Active = true,
         Age = 50,
         AutoId = 16,
         BirthDate = DateTime.Now,
         FirstName = "Sheo",
         LastName = "Narayan"
    };
    var setting = new Newtonsoft.Json.JsonSerializerSettings();
    setting.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

     return Json(Newtonsoft.Json.JsonConvert.SerializeObject(model, setting), JsonRequestBehavior.AllowGet);
}
In this case, we have instantiated the JsonSerializerSettings and set its ContractResolver property to CamelCasePropertyNameContractResolver instance. While returning the Json using SerializeObject method, we are passing its 2nd parameter to that setting. This will give following output, notice the property name, it is "autoId" not "AutoId" as in case of the 1st code snippet above.

"{\"autoId\":16,\"firstName\":\"Sheo\",\"lastName\":\"Narayan\",\"age\":50,\"active\":true,\"birthDate\":\"2015-12-14T08:18:46.0770567+05:30\"}"

Indenting the JSON string in C#

If our requirement is to indent the return JSON string, we can use Newtonsoft.Json.Formatting enumerations like this. Note that we can skip the setting parameter here if we do not want to specify any settings while returning the JSON data.

return Json(Newtonsoft.Json.JsonConvert.SerializeObject(model, Newtonsoft.Json.Formatting.Indented, setting), JsonRequestBehavior.AllowGet);
That will give the output like below, notice that each property is separated by new line character "\r\n".

"{\r\n  \"autoId\": 16,\r\n  \"firstName\": \"Sheo\",\r\n  \"lastName\": \"Narayan\",\r\n  \"age\": 50,\r\n  \"active\": true,\r\n  \"birthDate\": \"2015-12-14T08:27:29.1404555+05:30\"\r\n}"

Conclusion
To work with JSON, Newtonsoft.Json is a very handly third party component that help us to deal with many problems that come by default in JSON.


Feel free to write your feedback and comment for this article below. Keep learning and sharing knowledge!
Recommendation
Read WebGrid in ASP.NET MVC after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)