Quantcast
Channel: CodeProject Latest postings for Dominic Burford
Viewing all articles
Browse latest Browse all 280

Serializing .NET types that contain DateTime

$
0
0
I recently had to de-serialize a JSON string that contained a date. The object contained valid DateTime properties and was then serialised. When it was subsequently passed to the receiving application, the serialised object could not be de-serialised as the dates were not in a valid format.

Example of the problem.
//the client application serialises the datestring jsonDate = JavaScriptSerializer().Serialize(DateTime.Now);//the receiving application attempts to de-serialise the date
DateTime dt = new JavaScriptSerializer().Deserialize<DateTime>(jsonDate); //this throws an exception!
When viewing the JSON representation of the date it would appear as follows.
/Date(1484904895490)/
The fix I eventually managed to figure out that solved the problem was to use the JsonConvert.SerializeObject() function instead.
var isoConvert = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
DateTime dt = JsonConvert.SerializeObject(jsonDate, isoConvert);
This solution works with any object that contains dates (or even those that don't include dates). I now use this code in my serialization function throughout my application.
"There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult." - C.A.R. Hoare

Home | LinkedIn | Google+ | Twitter

Viewing all articles
Browse latest Browse all 280

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>