简体   繁体   English

为ASP.NET Web服务配置JSON序列化

[英]Configure JSON serialization for ASP.NET web service

I have a .asmx web service that communicates using JSON. 我有一个.asmx Web服务,它使用JSON进行通信。 From it I simply return objects which ASP.NET magically serializes into JSON. 通过它,我仅返回ASP.NET神奇地序列化为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: 我需要将它们以ISO8601格式进行序列化,如下所示:

"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? 目前,不能选择使用ASP.NET的Web API,所以我的问题是:是否可以通过一种方式来配置ASP.NET Web服务的默认JSON序列化程序,使其返回ISO8601日期?

In my ASMX files, I set the return type to void and then I do this... 在我的ASMX文件中,将返回类型设置为void,然后执行此操作...

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. 如果您正在运行Json.NET 4.5,则默认情况下应该已经具有ISO 8601日期格式。 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). 下面是您应该做的(确保将ASMX中的函数的返回类型设置为void)。

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 . 这基于Json.NET文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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