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

后端 未结 4 1656
离开以前
离开以前 2020-12-18 01:42

When I return object that contains DateTime property using

return Json(value);

on client I receive

\"/Date(1336618438854)/         


        
相关标签:
4条回答
  • 2020-12-18 02:18

    If you dont want to dig in to the Parsing thing than simply convert your date in to the string than parse it with the JSON.

    for example

    return Json(DateTime.Now.ToString("your date format if you want to specify"));
    
    0 讨论(0)
  • 2020-12-18 02:23

    It returns 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");
    

    };

    0 讨论(0)
  • 2020-12-18 02:28

    In the WebApiConfig set:

    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();
    

    In the ApiController return this:

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

    Good Luck CAhumada

    0 讨论(0)
  • 2020-12-18 02:37

    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.

    0 讨论(0)
提交回复
热议问题