I am currently working on a client-server system in C# and ASP.NET, which, among other things, passes DateTime objects back and forth as pasrt of a DataCOntract.
The API endpoint written using a ASP.NET Web API project accepts and returns JSON from the Windows client app. For some reason, the DataContractJSONSerializer in the client app doesn't accept the JSON-encapsulated DateTime object being pulled from the server.
Server output:
[
{"title":"My Object", "time":"2017-02-20T12:37:35.53" },
{"title":"My Second Object", "time":"2017-02-20T12:37:35.53" }
]
But the DataContractJsonSerializer expects the DateTime to be in a format like this:
\/Date(12345789)\/
How can I change one or the other?
-
1Possible duplicate of ASP.NET Web API Date format in JSON does not serialise successfullyIvan Kishchenko– Ivan Kishchenko2017年02月21日 11:39:29 +00:00Commented Feb 21, 2017 at 11:39
2 Answers 2
Have you specified the DateTime format settings for the serializer?
From Custom DateTime serialization/deserialization using DataContractJsonSerializer
var serializer = new DataContractJsonSerializer(
typeof(Client),
new DataContractJsonSerializerSettings {
DateTimeFormat = new DateTimeFormat("yyyy-mm-dd hh:MM:ss"),
});
2 Comments
I finally found a way to change the output of the Web API to return a custom format and specified this in the client app as well. As it turns out, it is possible to set the DateFormatString in the Register method of the WebApiConfig.cs like this:
config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-mm-dd HH:MM:ss";
Afterwords, applying the DateTimeFormat as mentioned in @uzr's answer makes sure that everything is on the right format. Thanks everyone for your help!