Skip to content

Instantly share code, notes, and snippets.

@jasmin-mistry
Created January 28, 2014 13:41
Show Gist options
  • Save jasmin-mistry/8667855 to your computer and use it in GitHub Desktop.
Save jasmin-mistry/8667855 to your computer and use it in GitHub Desktop.
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
TimeZoneInfo tzi = TimeZoneInfo.Local;
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj.SpecifyDateTimeKind());
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
public static T FromJSON<T>(string str)
{
T obj;
JavaScriptSerializer serializer = new JavaScriptSerializer();
obj = serializer.Deserialize<T>(str).SpecifyDateTimeKind();
return obj;
}
/// <summary>
/// All the datetime properties will be set to a DateTimeKind.UTC using SpecifyKind method.
/// This will correct the datetime value when serialized/deserialized using JavascriptSerializer.
/// This also takes care of nullable DateTime properties.
/// </summary>
/// <param name="obj">Any Object</param>
/// <returns></returns>
public static T SpecifyDateTimeKind<T>(this T obj)
{
Type t = obj.GetType();
// Loop through the properties.
PropertyInfo[] props = t.GetProperties();
for (int i = 0; i < props.Length; i++)
{
PropertyInfo p = props[i];
// If a property is DateTime or DateTime?, set DateTimeKind to DateTimeKind.Utc.
if (p.PropertyType == typeof(DateTime))
{
DateTime date = (DateTime)p.GetValue(obj, null);
date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
p.SetValue(obj, date, null);
}
// Same check for nullable DateTime.
else if (p.PropertyType == typeof(Nullable<DateTime>))
{
DateTime? date = (DateTime?)p.GetValue(obj, null);
DateTime? newDate = DateTime.SpecifyKind(date.Value, DateTimeKind.Utc);
p.SetValue(obj, newDate, null);
}
}
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment