简体   繁体   中英

Configure JSON serialization for ASP.NET web service

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM