力JSON.NET序列化的DateTime时包括毫秒(即使MS分量为零) [英] Force JSON.NET to include milliseconds when serializing DateTime (even if ms component is zero)

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

问题描述

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

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

有没有办法强制JSON.NET包括在系列化毫秒,即使日期时间的毫秒分量为零?

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

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

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