Web API 2 datetime object

Yes… datetime field type is complex. It’s one of the most notorious data type. It’s a developer’s hate-hate relationship (ie. there’s no love any time.. ever..) from crm timezone dependent date time field to integration.

Today i face with this one – i put up a web api that reads from database that serves data to a crm workflow assembly. so technology wise, server is running latest web api, and client is workflow assembly. long story short, trouble comes in serialization/deserialization. Normally, there’s no problem, unless ….

you have a date time field. so the webapi get returns a list of poco, with one field being datetime type. The string on the receiving end looks great, but DataContractJsonSerializer says it wants this ugly format: “\/Date(1496445804940-0400)\/”.

restriction is below:

  1. unless you get into ilmerge, sandbox workflow assembly cannot use newtonsoft json.net. So you’re stuck with DataContractJsonSerializer

After struggling for half a day, i found a solution. apparently, webapi2 serializes poco automatically for you to json before send it over the wire. Nice. Now, how. the latest of course! newton json.net library. Hence the nice format. However, DataContractJsonSerializer doesn’t know how to deserialize it.. so the solution –

get webapi 2 to use the old date time format:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;

Advertisements

About s1301950

Dynamics CRM Developer with more than 5 years of experience in both 4.0 and 2011. Specialized in customization and development in plugins, custom workflows and xrm javascript. Also have more than 10 years of asp.net development. Currently engaged in projects using asp.net/C# 4.0 with LINQ and Identity framework (WIF)
This entry was posted in Uncategorized. Bookmark the permalink.

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