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

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

问题描述

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

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

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

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

背景:对于这个 JSON 端点,我有一个非常慢的 Web 服务使用者.条件逻辑对消费者来说很昂贵,所以我想每次都提供相同的数据格式.

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.

推荐答案

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

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

如果你不使用 Web API,你可以通过创建一个 JsonSerializerSettings 的新实例来做同样的事情,如上所示添加 IsoDateTimeConverter 到它,然后将序列化器设置传递给 JsonConvert.SerializeObject().

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

注意:如果您正在序列化 DateTimeOffset 或本地 DateTime 并且想要包含时区偏移量,请替换引用的 'Z' 在上面的格式中带有一个不带引号的 K.请参阅自定义日期和时间格式字符串有关更多信息的文档.

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天全站免登陆