0

I've modified WebAPI JSON.Net serialization to use JavaScriptDateTimeConverter. The plan was to get jscript date object instead of ISO 8601 formatted string. But unfortunately when I do post request with jquery like this:

$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "#UrlToService",
        dataType: "json",
        data: JSON.stringify(args),
        success: function (data) {
            callSucceeded(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            BJ.GenericWebAPIFailMethod(jqXHR);
        }
    });

error: is entered, textStatus is parseerror and errorThrown is giving me this info: SyntaxError: JSON.parse: unexpected keyword return window.JSON.parse( data ); jquery-1.7.2.js (line 564)

Part of my returned json object looks like:

"CreatedOn": Date {Thu Jul 25 2013 12:54:36 GMT+0200 (Central Europe Standard Time)}
"DisplayName": "Toronto, ON, Canada"
"Description": "12:54"

so it is indeed formatting my date as requested, but is fails later on parsing.

Any thoughts how to achieve what I wanted?

p.s. This is how I did that, in global.asax (asp.net web forms):

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Converters.Add(new JavaScriptDateTimeConverter());
5
  • Why do you need/want to use the JavaScriptDateTimeConverter in your Web API? If you leave it as an ISO 8601 date, then after jQuery deserializes the response you can convert the date string to a Date object simply by doing var date = new Date(data.CreatedOn);. Commented Jul 25, 2013 at 22:08
  • the problem is that we used web methods before, and now we are moving that code to WebAPI. So I would have to change a lot of jscript code manually. Commented Jul 25, 2013 at 22:28
  • How did your old web methods format dates before you moved to Web API? Commented Jul 25, 2013 at 22:42
  • CreatedOn=/Date(1374749676000)/ is how it was returned before, which I can accomplish in WebAPI also. When I return it with WebAPI it stays like that. But when it is returned from web method it is converted to jscript object?! Commented Jul 26, 2013 at 14:07
  • Actually WebAPI returns: "\/Date(1374749676000)\/" maybe thats where the problem is? Commented Jul 26, 2013 at 14:53

1 Answer 1

2

Using the standard date converter, WebAPI serializes dates as strings in either ISO 8601 format or Microsoft format, depending on the serializer's DateFormatHandling setting.

Using IsoDateFormat, the JSON would look like this:

{ "CreatedOn" : "2013-07-26T10:33:16Z" }

Using MicrosoftDateFormat, the JSON would look like this:

{ "CreatedOn" : "/Date(1374749676000)/" }

On the client side, jQuery can deserialize JSON containing either of those two date formats, but it does not automatically convert the date strings into Date objects, as you saw.

If you swap out the standard date converter on the server for the JavaScriptDateTimeConverter, then the JSON will be rendered like this instead:

{ "CreatedOn" : new Date(1374749676000) }

This is technically invalid JSON (notice there are no quotes, and JSON does not have any other way to represent a date than as a string). jQuery cannot deserialize this format, and will throw an error.

As I understand it, you would use the JavaScriptDateTimeConverter if you intended to get the data as text and then pass it to exec() so that the whole string is interpreted as JavaScript directly.

var obj = eval('(' + data + ')');

This may not be the best solution though due to security concerns.

If you need your dates to be deserialized to Date objects by jQuery, I think your best bet is to stick with the ISO 8601 format and then use a jQuery extension to do the conversion on the client side. Here is a blog post which talks about how to do this and has some code. [Disclaimer: I have not used this solution myself, and cannot vouch for whether it works.]

Also, see this question which offers many different approaches to this problem.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for help, we decided to go with iso8601 :). One problem with that blog post is that it doesn't work with complex objects. So if we have an object that has one of its parameters of type date, that solution won't traverse all properties, but instead it will just return null. But it is a helpful reference if someone would like to write the parser himself...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.