Guest User

Untitled

a guest
May 20th, 2018
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. public class MyCustomContractResolver : DefaultContractResolver
  2. {
  3.  
  4.  
  5. protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  6. {
  7. JsonProperty property = base.CreateProperty(member, memberSerialization);
  8. property.ShouldSerialize = (instance => containsSomeValues(instance.GetType()
  9. .GetProperty(member.Name)
  10. .GetValue(instance, null)));
  11.  
  12. return property;
  13. }
  14. private bool containsSomeValues(object p)
  15. {
  16. if (p == null)
  17. {
  18. return false;
  19. }
  20.  
  21. if (p.GetType() == typeof(DateTime))
  22. {
  23. return true;
  24. }
  25.  
  26. if (p.GetType() == typeof(string))
  27. {
  28. if (String.IsNullOrEmpty(p.ToString()))
  29. {
  30. return false;
  31. }
  32.  
  33. else
  34. {
  35. return true;
  36. }
  37. }
  38.  
  39. /*
  40. * This block skips serialization of the empty list and lists with empty objects;
  41. * I'd like to serialize both of those as the empty array so it's commented out.
  42. *
  43. if (typeof(IEnumerable).IsAssignableFrom(p.GetType()))
  44. {
  45. bool containsValues = false;
  46. foreach (object o in (IEnumerable)p)
  47. {
  48. if (containsSomeValues(o))
  49. {
  50. containsValues = true;
  51. }
  52.  
  53. }
  54. return containsValues;
  55.  
  56. }
  57. */
  58.  
  59. if (p.GetType().GetProperties().Count() > 0)
  60. {
  61. foreach (PropertyInfo pi in p.GetType().GetProperties())
  62. {
  63. if (containsSomeValues(pi.GetValue(p, null)))
  64. {
  65. return true;
  66. }
  67. }
  68. return false;
  69. }
  70.  
  71. return true;
  72. }
  73. }
Add Comment
Please, Sign In to add comment