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

When I return an object containing the DateTime property using

return Json(value);

on the client i get

"/Date(1336618438854)/"

If I return the same value using

return Json(JsonConvert.SerializeObject(value));

then the returned serialized value (along with the serialized object) is known by the time zone:

"/Date(1336618438854-0400)/"

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

+5
source share
4 answers

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

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

ajax , :

    return Json(JsonConvert.SerializeObject(complexObjectInstance));

:

    jsObject = JSON.parse(result)

, , , JSON ASP.NET MVC Newtonsoft JSON.net ISO 8601, , : JSON-, ASP MVC3.

+8

WebApiConfig:

config.Formatters.Remove(config.Formatters.XmlFormatter);
        //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
        config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;

        config.MapHttpAttributeRoutes();

ApiController :

return Request.CreateResponse(HttpStatusCode.OK, obj);

CAhumada

0

Parsing, , JSON.

return Json(DateTime.Now.ToString("your date format if you want to specify"));
-2
source

It returns the server date format. You need to define your own function.

function jsonDateFormat(jsonDate) {

// Changed data format;
return (new Date(parseInt(jsonDate.substr(6)))).format("mm-dd-yyyy / h:MM tt");

};

-2
source

All Articles