Web Api 2中的JSON序列化不使用ISO 8601日期

Joh*_*ell 9 c# json.net asp.net-web-api

我正在使用WebApi 2将一些Json发送到客户端,并使用旧式Date序列而不是ISO 8601.

我正在看:

"current_period_start": "\/Date(1388153705)\/",
"current_period_end": "\/Date(1390832105)\/",
"start": "\/Date(1388332525)\/",
Run Code Online (Sandbox Code Playgroud)

我的Global.asax.cs看起来像这样:

        GlobalConfiguration.Configure(WebApiConfig.Register);
        var formatters = GlobalConfiguration.Configuration.Formatters;
        var jsonFormatter = formatters.JsonFormatter;
        var settings = jsonFormatter.SerializerSettings;
        settings.Converters.Add(new IsoDateTimeConverter());
        settings.Formatting = Formatting.Indented;
        settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Run Code Online (Sandbox Code Playgroud)

Mic*_*haC 3

Newtonsoft.Json 默认为 IsoDateTimeConverter。因此,即使您没有指定任何内容,您也应该获得正确的 Iso 格式(对我来说,您的代码也可以正常工作。)。

阅读此内容Scott 的博客,了解有关默认值的更多信息

您很可能再次在其他地方设置转换器,也许您正在使用一些具有特定设置的自定义转换器?或者您使用的是非常旧版本的 Newtonsoft.Json?

  • Web API 返回 '2016-01-01T00:00:00',它因 ISO8601 Regex http://codepen.io/anon/pen/WryLGe 而失败,如果我在末尾添加 Z,它就会通过。http://codepen.io/anon/pen/qbKLaV (5认同)
  • 问题最终出在使用的第 3 方程序集的类型 DateTime?直到日期序列化问题我才注意到。 (2认同)