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?

asked Feb 21, 2017 at 11:35
1

2 Answers 2

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"),
});
answered Feb 21, 2017 at 11:41

2 Comments

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.
@TobiasTimpe Check out msdn.microsoft.com/en-us/library/… for globlization and formatting options for DateTime to format the time in a desired format.
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!

answered Feb 21, 2017 at 12:20

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.