0

In a MVC controller I have a class with a public DateTimeOffset? Prop1 {get;set;} The class is instantiated by json that was passed from a controller method. So the value passed in is a string of ISO8601 format "YYYY-MM-DDThh:mm:ss+08:00".

For some reason the implicit conversion fails and returns null. I read somewhere that I have to use a "k custom formatter". How would i set that up as default for string->DateTimeOffset conversion?

Can i do it without explicitly calling TryParse?

WindowsMaker
  • 3,132
  • 7
  • 29
  • 46

1 Answers1

0

In an MVC controller, the default JSON serializer is the JavaScriptSerializer - which does not understand ISO8601 formatted values. It expects dates to be something like: \/Date(1337020200000+0530)\. The DataContractJsonSerializer used with WCF applications also expects this format.

To support ISO8601, the easiest thing to do is to switch to ASP.Net WebAPI, which uses JSON.Net for serialization. JSON.Net uses ISO8601 as the default (while still supporting the other format).

Here is an old-but-good article describing the differences.

If you must stick with an MVC Controller, you can replace the serializer with JSON.Net, as described here.

Also, it's worth noting that while WebAPI uses JSON.Net today, it is going to be used in MVC by default with the upcoming ASP.Net vNext.

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575