🌶 feat(JSON): 添加自定义 JSON 序列化配置

This commit is contained in:
喵你个汪呀 2025-08-20 19:56:22 +08:00
parent 064d91e4ce
commit 1439739e6c
2 changed files with 244 additions and 0 deletions

View File

@ -0,0 +1,19 @@
// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
namespace Admin.NET.Core;
/// <summary>
/// 自定义Json转换字段名
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class CustomJsonPropertyAttribute(string name) : Attribute
{
/// <summary>
/// 序列化名称
/// </summary>
public string Name { get; } = name;
}

View File

@ -0,0 +1,225 @@
// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;
namespace Admin.NET.Core;
/// <summary>
/// 自定义JSON属性名称转换器
/// </summary>
public class CustomJsonPropertyConverter : JsonConverter<object>
{
/// <summary>
/// 共享配置选项
/// </summary>
public static readonly JsonSerializerOptions Options = new()
{
Converters = { new CustomJsonPropertyConverter() },
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
ReferenceHandler = ReferenceHandler.IgnoreCycles,
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
};
/// <summary>
/// 缓存类型属性元数据
/// </summary>
private static readonly ConcurrentDictionary<Type, IReadOnlyList<PropertyMeta>> PropertyCache = new();
private readonly string _dateTimeFormat;
public CustomJsonPropertyConverter(string dateTimeFormat = "yyyy-MM-dd HH:mm:ss")
{
_dateTimeFormat = dateTimeFormat;
}
/// <summary>
/// 检查类型是否包含自定义属性
/// </summary>
/// <param name="typeToConvert"></param>
/// <returns></returns>
public override bool CanConvert(Type typeToConvert)
{
return PropertyCache.GetOrAdd(typeToConvert, type =>
type.GetProperties()
.Where(p => p.GetCustomAttribute<CustomJsonPropertyAttribute>() != null)
.Select(p => new PropertyMeta(p))
.ToList().AsReadOnly()
).Count > 0;
}
/// <summary>
/// JSON反序列化
/// </summary>
/// <param name="reader"></param>
/// <param name="typeToConvert"></param>
/// <param name="options"></param>
/// <returns></returns>
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var jsonDoc = JsonDocument.ParseValue(ref reader);
var instance = Activator.CreateInstance(typeToConvert);
var properties = PropertyCache.GetOrAdd(typeToConvert, BuildPropertyMeta);
foreach (var prop in properties)
{
if (jsonDoc.RootElement.TryGetProperty(prop.JsonName, out var value))
{
object propertyValue = prop.PropertyType switch
{
Type t when IsDateTimeType(t) => HandleDateTimeValue(value, t),
_ => JsonSerializer.Deserialize(value.GetRawText(), prop.PropertyType, options)
};
prop.SetValue(instance, propertyValue);
}
}
return instance;
}
/// <summary>
/// JSON序列化
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
writer.WriteStartObject();
var properties = PropertyCache.GetOrAdd(value.GetType(), BuildPropertyMeta);
foreach (var prop in properties)
{
var propertyValue = prop.GetValue(value);
writer.WritePropertyName(prop.JsonName);
if (propertyValue != null && IsDateTimeType(prop.PropertyType))
{
writer.WriteStringValue(FormatDateTime(propertyValue));
}
else
{
JsonSerializer.Serialize(writer, propertyValue, options);
}
}
writer.WriteEndObject();
}
/// <summary>
/// 构建属性元数据缓存
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static IReadOnlyList<PropertyMeta> BuildPropertyMeta(Type type)
{
return type.GetProperties()
.Where(p => p.GetCustomAttribute<CustomJsonPropertyAttribute>() != null)
.Select(p => new PropertyMeta(p))
.ToList().AsReadOnly();
}
/// <summary>
/// 处理DateTime类型值
/// </summary>
/// <param name="value"></param>
/// <param name="targetType"></param>
/// <returns></returns>
private object HandleDateTimeValue(JsonElement value, Type targetType)
{
var dateStr = value.GetString();
if (string.IsNullOrEmpty(dateStr)) return null;
var date = DateTime.Parse(dateStr);
return targetType == typeof(DateTimeOffset) ? new DateTimeOffset(date) : date;
}
/// <summary>
/// 格式化DateTime输出
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
private string FormatDateTime(object dateTime)
{
return dateTime switch
{
DateTime dt => dt.ToString(_dateTimeFormat),
DateTimeOffset dto => dto.ToString(_dateTimeFormat),
_ => dateTime?.ToString()
};
}
/// <summary>
/// 检查是否为DateTime类型
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static bool IsDateTimeType(Type type)
{
var actualType = Nullable.GetUnderlyingType(type) ?? type;
return actualType == typeof(DateTime) || actualType == typeof(DateTimeOffset);
}
/// <summary>
/// 属性元数据包装类
/// </summary>
private class PropertyMeta
{
private readonly PropertyInfo _property;
private readonly Func<object, object> _getter;
private readonly Action<object, object> _setter;
public string JsonName { get; }
public Type PropertyType => _property.PropertyType;
public PropertyMeta(PropertyInfo property)
{
_property = property;
// 获取自定义属性名或使用原属性名
JsonName = property.GetCustomAttribute<CustomJsonPropertyAttribute>()?.Name ?? property.Name;
// 编译表达式树优化属性访问性能
var instanceParam = Expression.Parameter(typeof(object), "instance");
// Getter表达式编译
var getterExpr = Expression.Lambda<Func<object, object>>(
Expression.Convert(
Expression.Property(
Expression.Convert(instanceParam, property.DeclaringType),
property),
typeof(object)),
instanceParam);
_getter = getterExpr.Compile();
// Setter表达式编译如果属性可写
if (property.CanWrite)
{
var valueParam = Expression.Parameter(typeof(object), "value");
var setterExpr = Expression.Lambda<Action<object, object>>(
Expression.Assign(
Expression.Property(
Expression.Convert(instanceParam, property.DeclaringType),
property),
Expression.Convert(valueParam, property.PropertyType)),
instanceParam, valueParam);
_setter = setterExpr.Compile();
}
}
public object GetValue(object instance) => _getter(instance);
public void SetValue(object instance, object value)
{
_setter?.Invoke(instance, value);
}
}
}