Multiple DateTime formats in JSON response

Topics: Web Api
Feb 15, 2012 at 6:52 AM

JSON does not support datetime data type. I am implementing an application which is designed to support multiple clients. Each client may have a different preferred format. this could be ISO 8601, RFC822, javascript-friendly Unix time, etc.

What would be the best approach to support multiple response formats based on client request ?

More specifically:

  1. How to denote and detect the desired format (e.g an X-header ?) ?
  2. How to implement the output formatting based on the requested format ?
Feb 15, 2012 at 9:33 AM

Like you pointed out there is no standard for dates in JSON, so I'd just pick one.  For our APIs we decided to go with readability and chose the ISO 8601 standard.  For JSONP we might convert it to something like the MS serializer does, or simply use a JS date parser.

But if you really wanna go down the road of allowing the client to specify the format I guess it's possible, but your data will be harder to cache :)
You could write a custom JSON formatter that inspects the X-header and changes date formatting based on that.

Just curious, why are you adapting your service to clients? That's usually a slippery design slope :)

Feb 15, 2012 at 9:37 AM

Just curious, why are you adapting your service to clients? That's usually a slippery design slope :)

It is a public service, so clients may vary significantly between one client to the other.

Feb 15, 2012 at 9:52 AM

Yes, but usually the clients adapt to a service.  A service should be an API, not a special version of the API for all needs?  Then you end up spending most your time chasing every whim of multiple clients.

Multiple formats (JSON, XML) I can understand though :)

Feb 15, 2012 at 10:24 AM

Did you have to implement a custom formatter for just a single format ? Another option ?

Can you share some of it ?

Feb 15, 2012 at 10:36 AM
Edited Feb 15, 2012 at 10:42 AM

I think this is just an issue with JSON, XML has a way to specify dates.

I'm still using the default MS formatter, but plan to move to JSON.NET + customize the datetime formatting.
Right now my resource types just have the dates as strings, and using the "s" formatting specifier when converting.

There are a few examples on how to use JSON.NET with the Web API, just been too lazy/busy with other problems to tackle this one yet :)

Feb 15, 2012 at 9:20 PM

I have implemented a custom formatter, which handles a single format.

Any idea how can I gain access to the request header within the formatter context ?

Feb 16, 2012 at 9:41 AM

Haven't tried this myself, but have you tried contentHeaders.GetValues("X-something")  ?

Feb 16, 2012 at 12:07 PM

I think these are the content headers of the response...

Feb 18, 2012 at 9:23 AM

Check out this new blog post by Henrik from the ASP team: http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net-with-asp-net-web-api.aspx