18

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

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

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

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?

Maggie Ying
10.2k2 gold badges37 silver badges37 bronze badges
asked Oct 17, 2012 at 14:28

2 Answers 2

48

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.

answered Oct 17, 2012 at 20:49

1 Comment

Thanks for that help. We will not be creating a custom date time converter, I just wanted to confirm that the format was not acceptable by Json.NET by default.
4

Just set globalization in web.config:

<globalization enableClientBasedCulture="false" requestEncoding="utf-8" responseEncoding="utf-8" culture="en-GB" uiCulture="en-GB"/>

and then, in Global.asax.cs> Application_Start, set JsonFormatter to use the current culture:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Culture = System.Globalization.CultureInfo.CurrentCulture;
answered Jan 20, 2016 at 16:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.