Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

c# - Force JSON.NET to include milliseconds when serializing DateTime (even if ms component is zero)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...