ASP.NET Web API Date format in JSON does not serialise successfully

后端 未结 2 1788
不知归路
不知归路 2020-12-06 00:28

All,

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

sampleO         


        
2条回答
  •  醉梦人生
    2020-12-06 01:17

    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.

    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:

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

    Custom DateTimeConverter:

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

    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.

提交回复
热议问题