Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Controller.Json DateTime Serialization vs NewtonSoft Json DateTime Serialization

When I return object that contains DateTime property using

return Json(value);

on client I receive

"/Date(1336618438854)/"

If i return the same value using

return Json(JsonConvert.SerializeObject(value));

then the returned serialized value (together with serialized object) is time zone aware:

"/Date(1336618438854-0400)/"

Is there any way to get consistent DateTime result without without double serialization? I read somewhere that MS will include Newtonsoft JSON into MVC?

like image 462
user1188755 Avatar asked May 10 '12 03:05

user1188755


1 Answers

I finally figured out what to do.
I will switch my project to ISO 8601 DateTime format. Serialization is done nicely with JSON.net, just by decorating the datetime property on the object with JsonConverter attribute.

    public class ComplexObject 
    {
        [JsonProperty]
        public string ModifiedBy { get; set; }
        [JsonProperty]
        [JsonConverter(typeof(IsoDateTimeConverter))]
        public DateTime Modified { get; set; }
        ...
     }

To return serialized object to the client ajax call I can do:

    return Json(JsonConvert.SerializeObject(complexObjectInstance));

and on the client:

    jsObject = JSON.parse(result)

Now I am thinking it would be probably simple to override default ASP.NET MVC default JSON serializer to us Newtonsoft JSON.net ISO 8601 serialization, and yes principle should be similar to this thread: Change Default JSON Serializer Used In ASP MVC3.

like image 178
user1188755 Avatar answered Oct 16 '22 13:10

user1188755