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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)