Techrocket9
Techrocket9

Reputation: 2066

Serialization of a .net DateTime object parsed from an SQL Server database to JSON String

I believe that my .NET 4.5 DateTime object is being incorrectly serialized by its ApiController in my ASP.NET MCV 4 web app. After retrieving a DataRow object from an SQL Server database I assign it to a DateTime member object in my CarrierObject.

StartTime = (DateTime)row["start_time"]

After this I add the CarrierObject to a list and return the list when all relevant entries have been processed. The ApiController converts the list to a JSON string for transmission.

When I perform the API call on the client and read the JSON output I get output in the form of 2013-06-03T22:49:21.66 While this looks fine at first glance, attempting to parse this on the client side with

var client = new HttpClient();
var uri = new Uri("http://555.55.55.55/test4/api/values");
Stream respStream = await client.GetStreamAsync(uri);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<CarrierObject>));
List<CarrierObject> feeds = (List<CarrierObject>)ser.ReadObject(respStream);

it fails with the exception

System.Runtime.Serialization.SerializationException was unhandled by user code
  HResult=-2146233076
  Message=There was an error deserializing the object of type System.Collections.Generic.List  ...  PublicKeyToken=null]]. DateTime content '2013-06-03T22:49:21' does not start with '\/Date(' and end with ')\/' as required for JSON.

It seems to be wanting something in the format /Date(1224043200000)/. While I could manually write a converter to produce the correct JSON format that would seem to defeat the purpose of the automatic serialization performed by the API controller and automatic deserialization performed by the DataContractJsonSerializer. Is there a way to make the DataContractJsonSerializer accept the format being produced by the API Controller or the opposite? Is there a different parser that I should be using?

Thank you for your time,

-- Techrocket9

Upvotes: 2

Views: 5184

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 457312

Date serialization has always been a rough point for DataContractJsonSerializer. Try JSON.NET instead.

This is one of the reasons that WebAPI decided to use JSON.NET by default, rather than the older DataContractJsonSerializer.

Upvotes: 7

aiapatag
aiapatag

Reputation: 3430

Looks like it's really a gotcha in DataContractJsonSerializer. You can try to implement what this guy did here. Or this answer for a similar question raised before.

Upvotes: 0

Related Questions