This project is read-only.

Multiple DateTime formats in JSON response

Topics: Web Api
Feb 15, 2012 at 7: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 10: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 10: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 10: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 11: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 11:36 AM
Edited Feb 15, 2012 at 11: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 10: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 10:41 AM

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

Feb 16, 2012 at 1:07 PM

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

Feb 18, 2012 at 10:23 AM

Check out this new blog post by Henrik from the ASP team: