在用JSON序列化對象是,會返回這個對象的全部屬性鍵值對,若是某個對象的屬性很是多,可是咱們須要獲取的JSON數據只是其中的兩三個屬性,這樣的狀況,咱們怎麼優化呢?html
具體實現方式json
using System; using System.Collections.Generic; using System.Web.Script.Serialization; public class Person { public string Name { get; set; } public int Age { get; set; } public double Meney { get; set; } public double Tex { get; set; } public DateTime Berthday { get; set; } } /**//// <summary> ///簡單實體 可變屬性序列化器 /// </summary> public class PropertyVariableJsonSerializer { readonly System.Web.Script.Serialization.JavaScriptSerializer _serializer = new JavaScriptSerializer(); /**//// <summary> /// json 序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="propertys"></param> /// <returns></returns> public string Serialize<T>(T obj, List<string> propertys) { _serializer.RegisterConverters(new[] { new PropertyVariableConveter(typeof(T), propertys) }); return _serializer.Serialize(obj); } } public class PropertyVariableConveter : JavaScriptConverter { private readonly List<Type> _supportedTypes = new List<Type>(); public PropertyVariableConveter(Type supportedType, List<string> propertys) { _supportedTypes.Add(supportedType); Propertys = propertys; } private List<string> Propertys { get; set; } public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { throw new Exception(" 這個暫時不支持 , 謝謝 "); } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { var dic = new Dictionary<string, object>(); var t = obj.GetType(); var properties = t.GetProperties(); foreach (var ite in properties) { string key = ite.Name; var v = t.GetProperty(key).GetValue(obj, null); if (Propertys == null || Propertys.Count <= 0) { dic.Add(key, v); continue; } if (Propertys.Contains(key)) { dic.Add(key, v); } } return dic; } public override IEnumerable<Type> SupportedTypes { get { return _supportedTypes; } } }
調用ide
在序列化一個對象時, 只序列化了咱們想要的兩個屬性, 實際對象有4個屬性優化
public static void aaa() { var p = new Person { Age = 20, Name = "www.studyofnet.com", Meney = 3, Tex = 1}; var s = new PropertyVariableJsonSerializer(); string result = s.Serialize<Person>(p, new List<string>() { "Name", "Age" }); }
參考資料:如何Json序列化對象的部分屬性 http://www.studyofnet.com/news/1234.htmlcode