I have an object, it has a DateTime property... I want to pass that object from an .ashx handler back to a webpage via AJAX/JSON... I don't want to use 3rd party controls...
when I do this:
new JavaScriptSerializer().Serialize(DateTime.Now);
I get this:
"/Date(1251385232334)/"
but I want "8/26/2009" (nevermind localization... my app is very localized, so my date formatting assumptions are not up for debate in this question). If I make/register a custom converter
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;
}
}
then I get this result (since the return value of the custom serialize method is a dictionary):
{"DateTime":"8/27/2009"}
so now in my Javascript, instead of doing
somePerson.Birthday
I have to do
somePerson.Birthday.DateTime
or
somePerson.Birthday["DateTime"]
how can I make the custom converter return a direct string so that I can have clean Javascript?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…