Custom JavaScriptConverter for DateTime?

前端 未结 10 727
走了就别回头了
走了就别回头了 2020-12-02 19:18

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..

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 19:36

    JavaScriptSerializer can definitely do what you desire.

    It's possible to customize the serialization performed by JavaScriptSerializer for any type by creating a custom converter and registering it with the serializer. If you have a class called Person, we could create a converter like so:

    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 SupportedTypes
        {
            get
            {
                return new[] { typeof(Person) };
            }
        }
    
        public override object Deserialize(IDictionary 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 Serialize(object obj, JavaScriptSerializer serializer)
        {
            Person p = (Person)obj;
            IDictionary serialized = new Dictionary();
            serialized["Name"] = p.Name;
            serialized["Birthday"] = p.Birthday.ToString(_dateFormat);
            return serialized;
        }
    }
    

    And use it like this:

    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(json);
    Console.WriteLine(String.Format("{0}, {1}", fromJson.Name, fromJson.Birthday)); 
    // User Name, 12/20/2010 12:00:00 AM
    

提交回复
热议问题