0

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?

Tobias Timpe
  • 720
  • 2
  • 13
  • 27
  • 1
    Possible duplicate of [ASP.NET Web API Date format in JSON does not serialise successfully](http://stackoverflow.com/questions/12936614/asp-net-web-api-date-format-in-json-does-not-serialise-successfully) – Ivan Kishchenko Feb 21 '17 at 11:39

2 Answers2

1

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"),
});
Community
  • 1
  • 1
uzr
  • 1,210
  • 1
  • 13
  • 26
  • This now gives me a different error. What would the format of the DateTime in the first example of mine then be? I can get as far as you mentioned, but I guess it's failing on the "T" and the milliseconds after the dot. – Tobias Timpe Feb 21 '17 at 11:46
  • 1
    @TobiasTimpe Check out https://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.fulldatetimepattern(v=vs.110).aspx for globlization and formatting options for DateTime to format the time in a desired format. – uzr Feb 21 '17 at 11:55
0

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!

Tobias Timpe
  • 720
  • 2
  • 13
  • 27