在JSON的ASP.NET Web API的日期格式不顺利连载 [英] ASP.NET Web API Date format in JSON does not serialise successfully

查看:298
本文介绍了在JSON的ASP.NET Web API的日期格式不顺利连载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有,

我们正在使用的ASP.NET Web API,我们有一个JSON基于REST的服务为有效载荷。如果我通过下面的日期为一个字符串例如

We are using ASP.NET Web API where we have a REST based service with JSON for the payload. If I pass the following Date as a string e.g

sampleObj: {
...
myDate: "31/12/2011 00:00:00",
...
}

如以JSON有效载荷的属性值时,日期属性获取deserialised成DateTime.MinValue。是字符串格式是否有效?

as an attribute value in the JSON payload, the date attribute gets deserialised into a DateTime.MinValue. Is the string format valid?

我们知道,格式为2012年10月17日7时45分零零秒串行化成功,但我们不能保证所有收到的日期将在此格式。什么是有效的选项?

We know the format "2012-10-17 07:45:00" serialises successfully but we cannot guarantee that all dates received will be in this format. What are the valid options?

推荐答案

在ASP.NET的Web API,可以通过JsonFormatter的SerializerSettings添加不同的Json.NET DateTimeConverters,使您的服务了解不同Da​​teTime格式。

In ASP.NET Web API, you can add different Json.NET DateTimeConverters through the JsonFormatter's SerializerSettings to make your service understand different DateTime format.

不过,我不认为这是从Json.NET默认DateTimeConverter这需要以这种格式31/12/2011 00:00:00。在这种情况下您实现您的自定义DateTimeConverter。

However, I do not think there is a default DateTimeConverter from Json.NET that takes in this format "31/12/2011 00:00:00". In this case you implement your custom DateTimeConverter.

WebApiConfig.cs:

WebApiConfig.cs:

        config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
             new IsoDateTimeConverter());
        config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
             new MyDateTimeConverter());

自定义DateTimeConverter:

Custom DateTimeConverter:

public class MyDateTimeConverter : DateTimeConverterBase
{
    //...
}  

有关如何编写自定义DateTimeConverter更多信息,我发现那个计算器可能对您有用的东西:
<一href=\"http://stackoverflow.com/questions/8639315/how-to-create-a-json-net-date-to-string-custom-converter\">How创建一个json.net日期为字符串自定义转换器。

For more information about how to write a custom DateTimeConverter, I found something on stackoverflow that you might find useful: How to create a json.net Date to String custom Converter.

这篇关于在JSON的ASP.NET Web API的日期格式不顺利连载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆