WCF, JSON and the DateTime

I'm playing with a WCF service that works with JSON. If you haven't done this already, it's fairly easy. In the web.config, make sure your service is using the webHttpBinding binding. Also you'll need an endpoint behavior that looks like this:

<endpointBehaviors>
  <behavior name="MyBehavior">
    <webHttp />
  </behavior>
</endpointBehaviors>

 

Also, you'll need to annotate your operation methods with an attribute that tells WCF to use JSON (otherwise it uses XML):

[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]

 

That's it.

I had some problems however with the DateTime type. Unfortunately JSON doesn't have a standard for dates so Microsoft chose its own way. Basically it looks like “/Date(1224043200000)/”; the number represents the count of milliseconds since epoch.  So when you're consuming your service, you'll have to deserialize this format yourself. You can find some suggestions here, I picked the simple:

new Date(parseInt(jsonDate.substr(6)))

So if the date is represented by the count of milliseconds since epoch, what happens with older dates? This gave me a headache today, trying to figure out why my service wasn't returning anything… I had forgotten some DateTime set to its default value, which in .NET is 0000-00-00 00:00… I wasn't getting any error message whatsoever so I was troubleshooting blindly and the date was the last place to look. Usually it's some object referencing some other object that shouldn't or something like that…

Another promising solution is to use the Json.NET library which offers a custom date time formatting which is more human readable, but I didn't try it out, I just made sure all my dates where properly set.

Hope this helps.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s