Created
October 28, 2010 18:43
-
-
Save subhasisrout/652028 to your computer and use it in GitHub Desktop.
JSON Serializer with custom Javascript converter (used to Datetime formatting)
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
namespace dotnet_topics3 | |
{ | |
public partial class JavascriptSerializerDemo : System.Web.UI.Page | |
{ | |
protected void Page_Load(object sender, EventArgs e) | |
{ | |
Person p1 = new Person() { Name = "Subhasis Rout", Age = 26, DOB = Convert.ToDateTime("1984/06/30") }; | |
Person p2 = new Person() { Name = "Jason Leung", Age = 30, DOB = null }; | |
List<Person> listPerson = new List<Person>() { p1, p2 }; | |
var ser = new JavaScriptSerializer(); | |
ser.RegisterConverters(new JavaScriptConverter[] {new DateTimeConverter()}); | |
//without the above line | |
//{"DOB":"\/Date(457381800000)\/","Age":26,"Name":"Subhasis Rout"} | |
//{"DOB":{"DateTime":"1984-06-30 00.00.00"},"Age":26,"Name":"Subhasis Rout"} (FORMATTED) | |
string str = ser.Serialize(listPerson); | |
} | |
} | |
public class DateTimeConverter : JavaScriptConverter | |
{ | |
public override IEnumerable<Type> SupportedTypes | |
{ | |
get { return new List<Type>() { typeof(DateTime), typeof(DateTime?) }; } | |
} | |
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) | |
{ | |
Dictionary<string, object> result = new Dictionary<string, object>(); | |
if (obj == null) return result; | |
result["DateTime"] = ((DateTime)obj).ToString("yyyy-MM-dd HH.mm.ss"); | |
return result; | |
} | |
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) | |
{ | |
if (dictionary.ContainsKey("DateTime")) | |
return new DateTime(long.Parse(dictionary["DateTime"].ToString()), DateTimeKind.Unspecified); | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment