I am developing an API to expose some data using ASP.NET Web API.
In one of the API, the client wants us to expose the date in yyyy-MM-dd
format. I don't want to change the global settings (e.g. GlobalConfiguration.Configuration.Formatters.JsonFormatter
) for that since it is very specific to this client. And I do developing that in a solution for multiple clients.
One of the solution that I could think of is to create a custom JsonConverter
and then put that to the property I need to do the custom formatting
e.g.
class ReturnObjectA
{
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime ReturnDate { get;set;}
}
Just wondering if there is some other easy way of doing that.
Best Answer
You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the
JsonConverter
attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-inIsoDateTimeConverter
that lets you specify the date format. Unfortunately, you can't set the format via theJsonConverter
attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass theIsoDateTimeConverter
, then specify the date format in the constructor of the subclass. Apply theJsonConverter
attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is
yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK
(as seen in the source code).