在用JSON序列化对象是,会返回这个对象的所有属性键值对,如果某个对象的属性非常多,但是我们需要获取的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; } } /**///简单实体 可变属性序列化器 /// public class PropertyVariableJsonSerializer { readonly System.Web.Script.Serialization.JavaScriptSerializer _serializer = new JavaScriptSerializer(); /**/// json 序列化 /// ////// /// /// public string Serialize (T obj, List propertys) { _serializer.RegisterConverters(new[] { new PropertyVariableConveter(typeof(T), propertys) }); return _serializer.Serialize(obj); } } public class PropertyVariableConveter : JavaScriptConverter { private readonly List _supportedTypes = new List (); public PropertyVariableConveter(Type supportedType, List propertys) { _supportedTypes.Add(supportedType); Propertys = propertys; } private List Propertys { get; set; } public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer) { throw new Exception(" 这个暂时不支持 , 谢谢 "); } public override IDictionary Serialize(object obj, JavaScriptSerializer serializer) { var dic = new Dictionary (); 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 SupportedTypes { get { return _supportedTypes; } } }
调用
在序列化一个对象时, 只序列化了我们想要的两个属性, 实际对象有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(p, new List () { "Name", "Age" }); }
参考资料:如何Json序列化对象的部分属性