1

I have a .asmx web service that communicates using JSON. From it I simply return objects which ASP.NET magically serializes into JSON.

The only issue is that dates are serialized like this:

"myDate": "\/Date(1388332525)\/"

And I need them to be serialized in an ISO8601 format, like this:

"myDate":"\/Date(2012-09-19T03:27:14)\/"

Using ASP.NET's Web API is not an option at this point, so my question is this: Is there a way to configure the default JSON serializer for ASP.NET web services in such a way that it will return ISO8601 dates?

Payton Staub
  • 487
  • 3
  • 10
  • What version of ASP.NET are you using? – Shaun Luttin Mar 24 '14 at 23:46
  • I'm using ASP.NET 4.5 – Payton Staub Mar 24 '14 at 23:58
  • Are you serializing custom classes? Are you using System.Runtime.Serialization.Json or Newtonsoft.Json? If you're using System.Runtime.Serialization.Json you can set the [DateTimeFormat property](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializersettings.datetimeformat%28v=vs.110%29.aspx). For Newtonsoft [see this](http://james.newtonking.com/json/help/index.html). – mason Mar 25 '14 at 00:07
  • That is where I run into questions. These are public web methods in a .ASMX file with ResponseFormat set to Json and I return a collection of custom class objects which get serialized (how or by what I don't know). I have NewtonSoft stuff in my Intellisense, but where would I set these configuration options if I'm not manually serializing the response? – Payton Staub Mar 25 '14 at 00:39

1 Answers1

2

In my ASMX files, I set the return type to void and then I do this...

MyCustomClass myObj=MyCustomClass.Load();
string myJson=JsonConvert.SerializeObject(myObj);
HttpContext.Current.Response.ContentType="application/json";
HttpContext.Current.Response.Write(myJson);

I do this so I have finer grained control over the output. If you're running Json.NET 4.5, then you should already have ISO 8601 date format by default. But let's say you're running an older version. Below is what you should do (make sure you set the return type to void for your function in the ASMX).

JsonSerializerSettings isoDateFormatSettings = new JsonSerializerSettings(){ DateFormatHandling = DateFormatHandling.IsoDateFormat };
MyCustomClass myObj=MyCustomClass.Load();
string myJson=JsonConvert.SerializeObject(myObj, isoDateFormatSettings);
HttpContext.Current.Response.ContentType="application/json";
HttpContext.Current.Response.Write(myJson);

This is based on the Json.NET documentation.

mason
  • 31,774
  • 10
  • 77
  • 121
  • Nice, now I can control the Json leaving the web service. The only problem is it seems to still (somehow) put '{"d":null}' onto the end of the response.. – Payton Staub Mar 25 '14 at 02:51
  • See [this](http://stackoverflow.com/questions/9939548/asp-net-ajax-returning-json-but-not-recognised-as-json) for that. – mason Mar 25 '14 at 03:08