asp.net – 使用json仅序列化对象的一部分

前端之家收集整理的这篇文章主要介绍了asp.net – 使用json仅序列化对象的一部分前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个名为MyObject的对象,它有几个属性. MyList是MyObject的列表,我使用linq查询填充,然后将MyList序列化为json.我最终得到这样的东西
  1. List<MyObject> MyList = new List<MyObject>();
  2.  
  3. MyList = TheLinqQuery(TheParam);
  4.  
  5. var TheJson = new System.Web.Script.Serialization.JavaScriptSerializer();
  6. string MyJson = TheJson.Serialize(MyList);

我想要做的是仅序列化MyObject的一部分.例如,我可能有Property1,Property2 …… Propertyn,我希望MyJson只包含Property3,Property5和Property8.

我想到了一种方法,通过创建一个只有我想要的属性的新对象,然后从那里创建一个新的序列化列表.这是最好的方式还是有更好/更快的方式?

谢谢.

解决方法

  1. // simple dummy object just showing what "MyObject" could potentially be
  2. public class MyObject
  3. {
  4. public String Property1;
  5. public String Property2;
  6. public String Property3;
  7. public String Property4;
  8. public String Property5;
  9. public String Property6;
  10. }
  11.  
  12. // custom converter that tells the serializer what to do when it sees one of
  13. // the "MyObject" types. Use our custom method instead of reflection and just
  14. // dumping properties.
  15. public class MyObjectConverter : JavaScriptConverter
  16. {
  17. public override object Deserialize(IDictionary<string,object> dictionary,Type type,JavaScriptSerializer serializer)
  18. {
  19. throw new ApplicationException("Serializable only");
  20. }
  21.  
  22. public override IDictionary<string,object> Serialize(object obj,JavaScriptSerializer serializer)
  23. {
  24. // create a variable we can push the serailized results to
  25. Dictionary<string,object> result = new Dictionary<string,object>();
  26.  
  27. // grab the instance of the object
  28. MyObject myobj = obj as MyObject;
  29. if (myobj != null)
  30. {
  31. // only serailize the properties we want
  32. result.Add("Property1",myobj.Property1);
  33. result.Add("Property3",myobj.Property3);
  34. result.Add("Property5",myobj.Property5);
  35. }
  36.  
  37. // return those results
  38. return result;
  39. }
  40.  
  41. public override IEnumerable<Type> SupportedTypes
  42. {
  43. // let the serializer know we can accept your "MyObject" type.
  44. get { return new Type[] { typeof(MyObject) }; }
  45. }
  46. }

然后你在哪里序列化:

  1. // create an instance of the serializer
  2. JavaScriptSerializer serializer = new JavaScriptSerializer();
  3. // register our new converter so the serializer knows how to handle our custom object
  4. serializer.RegisterConverters(new JavaScriptConverter[] { new MyObjectConverter() });
  5. // and get the results
  6. String result = serializer.Serialize(MyObjectInstance);

猜你在找的asp.Net相关文章