强制JSON.NET在序列化DateTime时包含毫秒(即使ms组件为零) [英] Force JSON.NET to include milliseconds when serializing DateTime (even if ms component is zero)

查看:197
本文介绍了强制JSON.NET在序列化DateTime时包含毫秒(即使ms组件为零)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JSON.NET直接从对象实例(不使用DateTime.ToString()与格式化程序)序列化DateTime值。



有没有办法强制JSON.NET在序列化中包含毫秒数,即使DateTime的毫秒组件为零?



背景:我的JSON端点的Web服务使用率非常低。条件逻辑对消费者而言是昂贵的,所以我想每次提供相同的数据格式。

解决方案

这个同样的问题在我目前的项目上。我们使用Web API(因此JSON.Net)来实现一个REST API。我们发现,当序列化 DateTime 对象时,JSON.Net从毫秒开始忽略尾随零,或者如果零是完全忽略,则从完全忽略毫秒。我们的客户期待一个固定长度的日期时间字符串,几毫秒为3位数。我们通过在 Application_Start()中执行以下操作来修复它:

  JsonSerializerSettings settings = HttpConfiguration.Formatters.JsonFormatter.SerializerSettings; 
IsoDateTimeConverter dateConverter = new IsoDateTimeConverter
{
DateTimeFormat =yyyy' - 'MM' - 'dd'T'HH':'mm':'ss.fff'Z'
};
settings.Converters.Add(dateConverter);

如果您不使用Web API,您可以通过创建一个新的 JsonSerializerSettings ,添加如下所示的 IsoDateTimeConverter ,然后将串行器设置传递给 JsonConvert注意:如果你要序列化一个 DateTimeOffset ,或者一个本地的 DateTime ,并且要包含时区偏移,请将以上格式的引用的'Z'替换为未引用 K
请参阅自定义日期和时间格式字符串在文档中了解更多信息。


I'm using JSON.NET to serialize DateTime values directly from object instances (not using DateTime.ToString() with formatter).

Is there a way to force JSON.NET to include milliseconds in the serialization even if the millisecond component of the DateTime is zero?

Background: I have a very slow web service consumer for this JSON endpoint. Conditional logic is expensive for the consumer, so I'd like to provide the same data formatting every time.

解决方案

We ran into this same issue on my current project. We are using Web API (and hence JSON.Net) to implement a REST API. We discovered that, when serializing DateTime objects, JSON.Net omits the trailing zeros from the milliseconds, or omits the milliseconds from the date entirely if it is zero. Our clients were expecting a fixed-length date-time string, with exactly 3 digits for the milliseconds. We fixed it by doing the following in Application_Start():

JsonSerializerSettings settings = HttpConfiguration.Formatters.JsonFormatter.SerializerSettings;
IsoDateTimeConverter dateConverter = new IsoDateTimeConverter 
{ 
    DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'" 
};
settings.Converters.Add(dateConverter);

If you're not using Web API, you can do the same thing by creating a new instance of JsonSerializerSettings, adding the IsoDateTimeConverter to it as shown above, then passing the serializer settings to JsonConvert.SerializeObject().

Note: If you're serializing a DateTimeOffset or a local DateTime and you want to include the timezone offset, replace the quoted 'Z' in the above format with an unquoted K. See Custom Date and Time Format Strings in the documentation for more info.

这篇关于强制JSON.NET在序列化DateTime时包含毫秒(即使ms组件为零)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆