public class JavaScriptSerilizeConvert : JavaScriptConverter { //支持的須要轉換的類型,是集合能夠是多個 public override IEnumerable<Type> SupportedTypes => new List<Type>(new Type[] { typeof(Entity) }); public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { //這樣寫,無論什麼類型的對象都能反序列化了 var t = Activator.CreateInstance(type); var props = type.GetProperties(); if (dictionary != null) { foreach (var item in dictionary) { //這裏有可能大小寫不一樣, //兼容大小寫 var p = props.Where(a => a.Name.ToLower() == item.Key.ToLower()).ToList(); if(p.Count>1) p = props.Where(a => a.Name== item.Key).ToList(); if (p.Count > 0) { int val = 0; if (p[0].PropertyType == typeof(int)) { if (int.TryParse(item.Value.ToString(), out val)) { p[0].SetValue(t, val); } }// else if double 這裏要判斷double 其餘也同樣 else { p[0].SetValue(t, item.Value); } } } return t; } return null; } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { //不一樣的類型實體能夠作不一樣的處理 if (obj is Entity) { Entity t = obj as Entity; var dic= new Dictionary<string, object>(); var type = t.GetType(); var props = type.GetProperties(); foreach (var item in props) { var val = item.GetValue(obj); if (val != null) { dic.Add(item.Name, val); } } return dic; } else { return new Dictionary<string, object>(); } } }
static void Main(string[] args) { JavaScriptSerializer serializer = new JavaScriptSerializer(); var entity = new Entity(); entity.Id = 1; entity.Name = null; entity.Des = "123"; 能夠註冊多個自定義轉換器 serializer.RegisterConverters(new JavaScriptConverter[] { new JavaScriptSerilizeConvert() }); var str = serializer.Serialize(entity); Console.WriteLine(str); //這裏須要注意 通常在不用轉換器的狀況下 若是實體裏屬性Id的類型是int類型, //這裏2出就不要加雙引號,否則報錯 //我這裏在自定義轉換器上作了處理,因此可以把string類型的2轉換成int型。 var str2 = "{ \"Id\":\"2\",\"Name\":null,\"Des\":\"\"}"; var en2 = serializer.Deserialize<Entity>(str2); Console.WriteLine(en2.Id); Console.ReadLine(); }
public class Entity { public int Id { get; set; } public string Name { get; set; } public string Des { get; set; } }
這是簡單的實體,若是有實體嵌套,也不要緊,若是是都不序列化null,public override IEnumerable<Type> SupportedTypes => new List<Type>(new Type[] { typeof(Entity),typeof(SubEntity) });這裏加上就行ide