JsonMemberInfo.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // JsonKit v0.5 - A simple but flexible Json library in a single .cs file.
  2. //
  3. // Copyright (C) 2014 Topten Software (contact@toptensoftware.com) All rights reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product
  6. // except in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed under the
  11. // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. // either express or implied. See the License for the specific language governing permissions
  13. // and limitations under the License.
  14. using System;
  15. using System.Reflection;
  16. namespace Topten.JsonKit
  17. {
  18. // Information about a field or property found through reflection
  19. class JsonMemberInfo
  20. {
  21. public JsonMemberInfo()
  22. {
  23. }
  24. // The Json key for this member
  25. public string JsonKey;
  26. // True if should keep existing instance (reference types only)
  27. public bool KeepInstance => Attribute?.KeepInstance ?? false;
  28. // True if deprecated
  29. public bool Deprecated => Attribute?.Deprecated ?? false;
  30. // True if should be excluded when null
  31. public bool ExcludeIfNull => Attribute?.ExcludeIfNull ?? false;
  32. // True if should be excluded when collection is empty
  33. public bool ExcludeIfEmpty => Attribute?.ExcludeIfEmpty ?? false;
  34. // True if should be excluded when value is equal to a specified value
  35. public object ExcludeIfEquals => Attribute?.ExcludeIfEquals;
  36. // The JSON attribute for the member info
  37. public JsonAttribute Attribute
  38. {
  39. get;
  40. set;
  41. }
  42. // Reflected member info
  43. MemberInfo _mi;
  44. public MemberInfo Member
  45. {
  46. get { return _mi; }
  47. set
  48. {
  49. // Store it
  50. _mi = value;
  51. // Also create getters and setters
  52. if (_mi is PropertyInfo)
  53. {
  54. GetValue = (obj) => ((PropertyInfo)_mi).GetValue(obj, null);
  55. SetValue = (obj, val) => ((PropertyInfo)_mi).SetValue(obj, val, null);
  56. }
  57. else
  58. {
  59. GetValue = ((FieldInfo)_mi).GetValue;
  60. SetValue = ((FieldInfo)_mi).SetValue;
  61. }
  62. }
  63. }
  64. // Member type
  65. public Type MemberType
  66. {
  67. get
  68. {
  69. if (Member is PropertyInfo)
  70. {
  71. return ((PropertyInfo)Member).PropertyType;
  72. }
  73. else
  74. {
  75. return ((FieldInfo)Member).FieldType;
  76. }
  77. }
  78. }
  79. // Get/set helpers
  80. public Action<object, object> SetValue;
  81. public Func<object, object> GetValue;
  82. }
  83. }