5

How can I find the source of this problem, where a date value serialized by JavaScriptSerializer cannot be deserialized by the JavaScriptSerializer?

In the calling application:

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(model);

// generates this json
{'Guid':'guid','OrderNumber':'1','OrderDate':'\/Date(1299456000000)\/',
   'OrderStatus':'Completed','DiscountRate':0.0000}

In the receiving application:

string json = @"{'Guid':'guid','OrderNumber':'1','OrderDate':'\/Date(1299456000000)\/',
                 'OrderStatus':'Completed','DiscountRate':0.0000}";
var serializer = new JavaScriptSerializer();
var model = serializer.Deserialize(json);

Throws a String was not recognized as a valid DateTime exception.

If a date is serialized by JavaScriptSerializer then why can it not be deserialized by JavaScriptSerializer?

JK.
  • 21,477
  • 35
  • 135
  • 214
  • Have you seen this related question: http://stackoverflow.com/questions/1224793/javascript-serialization-of-datetime-in-asp-net-is-not-giving-a-javascript-date? – M.Babcock Dec 18 '11 at 22:30
  • 2
    I read that and lots of other questions but still don't understand why .NET can't deserialize something that was serialized by .NET? And I'm still unsure what I need to do. The client app is not mine, so I cant always tell them to change how they serialize it. – JK. Dec 18 '11 at 22:57
  • Try using `System.Runtime.Serialization.Json.DataContractJsonSerializer` instead. I just tried it and it didn't have any problems serializing and deserializing dates. – hawkke Dec 19 '11 at 00:08

1 Answers1

2

If model is of type Model then try specifying the type in the call to Deserialize.

string json = @"{'Guid':'guid','OrderNumber':'1','OrderDate':'\/Date(1299456000000)\/',
             'OrderStatus':'Completed','DiscountRate':0.0000}";
var serializer = new JavaScriptSerializer();
var model = serializer.Deserialize<Model>(json);

I'm able to serialize and deserialize dates with no errors this way.

Nick Sarabyn
  • 1,632
  • 2
  • 21
  • 29