Created
January 28, 2014 13:41
-
-
Save jasmin-mistry/8667855 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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