Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScriptSerializer.Deserialize does not accept a date that was serialized by JavaScriptSerializer.Serialize

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?

like image 230
JK. Avatar asked Nov 04 '22 09:11

JK.


1 Answers

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.

like image 181
Nick Sarabyn Avatar answered Nov 09 '22 13:11

Nick Sarabyn