Correcting Dates That Have Been Serialized to JSON

The Problem

The issue with dates in JSON, is that whenever you serialize, say a C# DateTime object, the date comes out in an unexpected format. Observe the output when a date of June 10, 2013 8:45:43PM is serialized to JSON:

DateTime date = new DateTime(2013, 6, 10, 20, 45,43);
String jsonDate = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(date);
// jsonDate = "/Date(1370897143000)/";

In this post we’ll look at how to fix this so that the date can be displayed or manipulated properly in the front-end.

Continue reading

JSON + C# Objects: Serializing and Deserializing

What’s it for?

JSON is great for storing large amounts of data into a single string. Facebook and a host of other major services store, serve and consume JSON as their primary means of data communication. With JSON you can actually deserialize an object such as a custom MyCustomer object and save it directly as JSON.

Serializing a C# Object into JSON

Serializing an object to JSON can be accomplished with just two lines of code. In the following example, we look at how to serialize a custom UserPreferences object:

UserPreferences preferences = new UserPreferences();
//set some values

//serialize
System.Web.Script.Serialization.JavaScriptSerializer serializer = new JavaScriptSerializer();
String JSONdata = serializer.Serialize(preferences);

From here, we are now ready to do all sorts of cool things with JSON. Please note that said cool things are outside of the scope of this post, so I will leave it to you to explore.

Deserializing JSON back into C# Object

Deserializing JSON back in an object is also easily accomplished in just two measly lines of code (actually, it can be done in 1 line.) In the following example, we deserialize the JSON equivilant of our UserPreferences object back into a C# object.

JavaScriptSerializer serializer = new JavaScriptSerializer();
UserPreferences preferences = serializer.Deserialize<UserPreferences>(JSONdata);

Many examples on deserializing JSON to C# Objects will tell you to use DeserializeObject() instead, but this gives you an Object object which then has to be casted to our UserPreferences object. If you already know what type of Object the JSON data is, the method outlined above is the way to go.