我有一个对象,它具有DateTime属性…我想将该对象从.ashx处理程序通过AJAX / JSON传递回网页…我不想使用第三方控件…
当我这样做时:
new JavaScriptSerializer().Serialize(DateTime.Now);
我得到这个:
"\/Date(1251385232334)\/"
但是我想输入“ 2009年8月26日”(不要介意本地化…我的应用程序非常本地化,因此我的日期格式设置假设不值得在这个问题上进行辩论)。如果我制作/注册自定义转换器
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; } }
然后得到这个结果(因为自定义序列化方法的返回值是一个字典):
{"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, object> dictionary, Type type, 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, object> Serialize(object obj, 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