CustomJsonPropertyConverter.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using System.Text.Json;
  7. using System.Text.Json.Serialization;
  8. namespace Admin.NET.Core;
  9. /// <summary>
  10. /// 自定义属性名称转换器
  11. /// </summary>
  12. public class CustomJsonPropertyConverter : JsonConverter<object>
  13. {
  14. public static readonly JsonSerializerOptions Options = new()
  15. {
  16. Converters = { new CustomJsonPropertyConverter() },
  17. DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
  18. };
  19. // 缓存类型信息避免重复反射
  20. private static readonly ConcurrentDictionary<Type, IReadOnlyList<PropertyMeta>> PropertyCache = new();
  21. // 日期时间格式化配置
  22. private readonly string _dateTimeFormat;
  23. public CustomJsonPropertyConverter(string dateTimeFormat = "yyyy-MM-dd HH:mm:ss")
  24. {
  25. _dateTimeFormat = dateTimeFormat;
  26. }
  27. public override bool CanConvert(Type typeToConvert)
  28. {
  29. return PropertyCache.GetOrAdd(typeToConvert, type =>
  30. type.GetProperties()
  31. .Where(p => p.GetCustomAttribute<CustomJsonPropertyAttribute>() != null)
  32. .Select(p => new PropertyMeta(p))
  33. .ToList().AsReadOnly()
  34. ).Count > 0;
  35. }
  36. public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  37. {
  38. var jsonDoc = JsonDocument.ParseValue(ref reader);
  39. var instance = Activator.CreateInstance(typeToConvert);
  40. var properties = PropertyCache.GetOrAdd(typeToConvert, BuildPropertyMeta);
  41. foreach (var prop in properties)
  42. {
  43. if (jsonDoc.RootElement.TryGetProperty(prop.JsonName, out var value))
  44. {
  45. object propertyValue;
  46. // 特殊处理日期时间类型
  47. if (IsDateTimeType(prop.PropertyType))
  48. {
  49. propertyValue = HandleDateTimeValue(value, prop.PropertyType);
  50. }
  51. else
  52. {
  53. propertyValue = JsonSerializer.Deserialize(
  54. value.GetRawText(),
  55. prop.PropertyType,
  56. options
  57. );
  58. }
  59. prop.SetValue(instance, propertyValue);
  60. }
  61. }
  62. return instance;
  63. }
  64. public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
  65. {
  66. writer.WriteStartObject();
  67. var properties = PropertyCache.GetOrAdd(value.GetType(), BuildPropertyMeta);
  68. foreach (var prop in properties)
  69. {
  70. var propertyValue = prop.GetValue(value);
  71. writer.WritePropertyName(prop.JsonName);
  72. // 特殊处理日期时间类型
  73. if (propertyValue != null && IsDateTimeType(prop.PropertyType))
  74. {
  75. writer.WriteStringValue(FormatDateTime(propertyValue));
  76. }
  77. else
  78. {
  79. JsonSerializer.Serialize(writer, propertyValue, options);
  80. }
  81. }
  82. writer.WriteEndObject();
  83. }
  84. private static IReadOnlyList<PropertyMeta> BuildPropertyMeta(Type type)
  85. {
  86. return type.GetProperties()
  87. .Select(p => new PropertyMeta(p))
  88. .ToList().AsReadOnly();
  89. }
  90. private object HandleDateTimeValue(JsonElement value, Type targetType)
  91. {
  92. var dateStr = value.GetString();
  93. if (string.IsNullOrEmpty(dateStr)) return null;
  94. var date = DateTime.Parse(dateStr);
  95. return targetType == typeof(DateTimeOffset)
  96. ? new DateTimeOffset(date)
  97. : (object)date;
  98. }
  99. private string FormatDateTime(object dateTime)
  100. {
  101. return dateTime switch
  102. {
  103. DateTime dt => dt.ToString(_dateTimeFormat),
  104. DateTimeOffset dto => dto.ToString(_dateTimeFormat),
  105. _ => dateTime?.ToString()
  106. };
  107. }
  108. private static bool IsDateTimeType(Type type)
  109. {
  110. var actualType = Nullable.GetUnderlyingType(type) ?? type;
  111. return actualType == typeof(DateTime) || actualType == typeof(DateTimeOffset);
  112. }
  113. private class PropertyMeta
  114. {
  115. private readonly PropertyInfo _property;
  116. private readonly Func<object, object> _getter;
  117. private readonly Action<object, object> _setter;
  118. public string JsonName { get; }
  119. public Type PropertyType => _property.PropertyType;
  120. public PropertyMeta(PropertyInfo property)
  121. {
  122. _property = property;
  123. JsonName = property.GetCustomAttribute<CustomJsonPropertyAttribute>()?.Name ?? property.Name;
  124. // 编译表达式树优化属性访问
  125. var instanceParam = Expression.Parameter(typeof(object), "instance");
  126. var valueParam = Expression.Parameter(typeof(object), "value");
  127. // Getter
  128. var getterExpr = Expression.Lambda<Func<object, object>>(
  129. Expression.Convert(
  130. Expression.Property(
  131. Expression.Convert(instanceParam, property.DeclaringType),
  132. property),
  133. typeof(object)),
  134. instanceParam);
  135. _getter = getterExpr.Compile();
  136. // Setter
  137. if (property.CanWrite)
  138. {
  139. var setterExpr = Expression.Lambda<Action<object, object>>(
  140. Expression.Assign(
  141. Expression.Property(
  142. Expression.Convert(instanceParam, property.DeclaringType),
  143. property),
  144. Expression.Convert(valueParam, property.PropertyType)),
  145. instanceParam, valueParam);
  146. _setter = setterExpr.Compile();
  147. }
  148. }
  149. public object GetValue(object instance) => _getter(instance);
  150. public void SetValue(object instance, object value)
  151. {
  152. if (_setter != null)
  153. {
  154. _setter(instance, value);
  155. }
  156. }
  157. }
  158. }