我有一个对象,它有一个DateTime属性…我想将该对象从.ashx处理程序通过AJAX / JSON传递到一个网页…我不想使用第三方控件…
当我这样做:
new JavaScriptSerializer().Serialize(DateTime.Now);
我得到这个:
"\/Date(1251385232334)\/"
但是我想要“8/26/2009”(不管本地化…我的应用程序是非常本地化的,所以我的日期格式化假设不是在这个问题上辩论)。如果我注册一个自定义转换器
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).ToShortDateString(); 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; } }
那么我得到这个结果(由于自定义serialize方法的返回值是字典):
{"DateTime":"8/27/2009"}
所以现在在我的Javascript,而不是做
somePerson.Birthday
我要做
somePerson.Birthday.DateTime or somePerson.Birthday["DateTime"]
如何使自定义转换器返回一个直接的字符串,以便我可以有干净的Javascript?
JavaScriptSerializer绝对可以做你想要的。
可以通过创建自定义转换器并将其注册到序列化程序来定制JavaScriptSerializer对任何类型执行的序列化。如果你有一个类叫做Person,我们可以创建一个如下的转换器:
public class Person { public string Name { get; set; } public DateTime Birthday { get; set; } } public class PersonConverter : JavaScriptConverter { private const string _dateFormat = "MM/dd/yyyy"; public override IEnumerable<Type> SupportedTypes { get { return new[] { typeof(Person) }; } } public override object Deserialize(IDictionary<string,JavaScriptSerializer serializer) { Person p = new Person(); foreach (string key in dictionary.Keys) { switch (key) { case "Name": p.Name = (string)dictionary[key]; break; case "Birthday": p.Birthday = DateTime.ParseExact(dictionary[key] as string,_dateFormat,DateTimeFormatInfo.InvariantInfo); break; } } return p; } public override IDictionary<string,JavaScriptSerializer serializer) { Person p = (Person)obj; IDictionary<string,object> serialized = new Dictionary<string,object>(); serialized["Name"] = p.Name; serialized["Birthday"] = p.Birthday.ToString(_dateFormat); return serialized; } }
并使用它像这样:
JavaScriptSerializer serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new PersonConverter() }); Person p = new Person { Name = "User Name",Birthday = DateTime.Now }; string json = serializer.Serialize(p); Console.WriteLine(json); // {"Name":"User Name","Birthday":"12/20/2010"} Person fromJson = serializer.Deserialize<Person>(json); Console.WriteLine(String.Format("{0},{1}",fromJson.Name,fromJson.Birthday)); // User Name,12/20/2010 12:00:00 AM