如何为值对象序列化创建System.Text.Json通用JsonConverter
基于System.Text.Json的通用DDD值对象JsonConverter实现方案
实现思路
要兼顾通用性和性能,核心采用「类型元数据缓存+表达式树编译委托」的方案,避免每次序列化/反序列化时的反射开销,同时适配单属性、多属性两类值对象的序列化需求:
- 单属性值对象(如示例中的
MeetingId):序列化直接输出属性值,不嵌套JSON对象 - 多属性值对象(如示例中的
MeetingTerm):序列化时将属性扁平化写入父级JSON对象,反序列化时从父级读取对应属性构造值对象
核心代码实现
第一步:实现转换器工厂
using System.Collections.Concurrent; using System.Linq.Expressions; using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; public class ValueObjectConverterFactory : JsonConverterFactory { private static readonly ConcurrentDictionary<Type, JsonConverter> _converterCache = new(); private static readonly Type _valueObjectBaseType = typeof(ValueObject); public override bool CanConvert(Type typeToConvert) { return _valueObjectBaseType.IsAssignableFrom(typeToConvert) && typeToConvert != _valueObjectBaseType; } public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { return _converterCache.GetOrAdd(typeToConvert, type => { var converterType = typeof(ValueObjectConverter<>).MakeGenericType(type); return (JsonConverter)Activator.CreateInstance(converterType, options)!; }); } }
第二步:实现泛型值对象转换器
public class ValueObjectConverter<T> : JsonConverter<T> where T : ValueObject { // 缓存序列化委托:输入值对象、Utf8JsonWriter、JsonSerializerOptions,无返回值 private readonly Action<T, Utf8JsonWriter, JsonSerializerOptions> _serializeDelegate; // 缓存反序列化委托:输入JsonElement、JsonSerializerOptions,返回值对象实例 private readonly Func<JsonElement, JsonSerializerOptions, T> _deserializeDelegate; // 是否为单属性值对象 private readonly bool _isSingleValueObject; // 单属性值对象的唯一属性信息 private readonly PropertyInfo? _singleValueProperty; public ValueObjectConverter(JsonSerializerOptions options) { var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanRead) .ToList(); _isSingleValueObject = properties.Count == 1; _singleValueProperty = _isSingleValueObject ? properties[0] : null; // 编译序列化委托 _serializeDelegate = BuildSerializeDelegate(properties, options); // 编译反序列化委托 _deserializeDelegate = BuildDeserializeDelegate(properties, options); } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { if (value == null) { writer.WriteNullValue(); return; } _serializeDelegate(value, writer, options); } public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var doc = JsonDocument.ParseValue(ref reader); return _deserializeDelegate(doc.RootElement, options); } // 表达式树构建序列化委托,避免反射开销 private Action<T, Utf8JsonWriter, JsonSerializerOptions> BuildSerializeDelegate(List<PropertyInfo> properties, JsonSerializerOptions options) { var valueParam = Expression.Parameter(typeof(T), "value"); var writerParam = Expression.Parameter(typeof(Utf8JsonWriter), "writer"); var optionsParam = Expression.Parameter(typeof(JsonSerializerOptions), "options"); var statements = new List<Expression>(); if (_isSingleValueObject) { // 单属性直接写值 var propertyAccess = Expression.Property(valueParam, _singleValueProperty!); var writeMethod = typeof(JsonSerializer).GetMethod(nameof(JsonSerializer.Serialize), new[] { typeof(Utf8JsonWriter), typeof(object), typeof(Type), typeof(JsonSerializerOptions) })!; statements.Add(Expression.Call(writeMethod, writerParam, Expression.Convert(propertyAccess, typeof(object)), Expression.Constant(_singleValueProperty.PropertyType), optionsParam)); } else { // 多属性扁平化写入 foreach (var prop in properties) { var propName = options.PropertyNamingPolicy?.ConvertName(prop.Name) ?? prop.Name; var propertyAccess = Expression.Property(valueParam, prop); var writeMethod = typeof(Utf8JsonWriter).GetMethod($"Write{prop.PropertyType.Name}", new[] { typeof(string), prop.PropertyType }) ?? typeof(JsonSerializer).GetMethod(nameof(JsonSerializer.Serialize), new[] { typeof(Utf8JsonWriter), typeof(object), typeof(Type), typeof(JsonSerializerOptions) })!; Expression writeCall; if (writeMethod.DeclaringType == typeof(Utf8JsonWriter)) { writeCall = Expression.Call(writerParam, writeMethod, Expression.Constant(propName), propertyAccess); } else { writeCall = Expression.Call(writeMethod, writerParam, Expression.Convert(propertyAccess, typeof(object)), Expression.Constant(prop.PropertyType), optionsParam); } statements.Add(writeCall); } } return Expression.Lambda<Action<T, Utf8JsonWriter, JsonSerializerOptions>>( Expression.Block(statements), valueParam, writerParam, optionsParam).Compile(); } // 表达式树构建反序列化委托 private Func<JsonElement, JsonSerializerOptions, T> BuildDeserializeDelegate(List<PropertyInfo> properties, JsonSerializerOptions options) { var elementParam = Expression.Parameter(typeof(JsonElement), "element"); var optionsParam = Expression.Parameter(typeof(JsonSerializerOptions), "options"); if (_isSingleValueObject) { // 单属性直接反序列化值构造对象 var deserializeMethod = typeof(JsonSerializer).GetMethod(nameof(JsonSerializer.Deserialize), new[] { typeof(JsonElement), typeof(Type), typeof(JsonSerializerOptions) })!; var valueExpression = Expression.Call(deserializeMethod, elementParam, Expression.Constant(_singleValueProperty!.PropertyType), optionsParam); // 匹配值对象只有一个参数的公开构造函数 var ctor = typeof(T).GetConstructors(BindingFlags.Public | BindingFlags.Instance) .First(c => c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == _singleValueProperty.PropertyType); var newExpression = Expression.New(ctor, Expression.Convert(valueExpression, _singleValueProperty.PropertyType)); return Expression.Lambda<Func<JsonElement, JsonSerializerOptions, T>>(newExpression, elementParam, optionsParam).Compile(); } else { // 多属性读取对应值构造对象 var ctor = typeof(T).GetConstructors(BindingFlags.Public | BindingFlags.Instance) .OrderByDescending(c => c.GetParameters().Length) .First(); var ctorParams = ctor.GetParameters(); var arguments = new List<Expression>(); foreach (var param in ctorParams) { var prop = properties.First(p => string.Equals(p.Name, param.Name, StringComparison.OrdinalIgnoreCase) && p.PropertyType == param.ParameterType); var propName = options.PropertyNamingPolicy?.ConvertName(prop.Name) ?? prop.Name; var getPropertyMethod = typeof(JsonElement).GetMethod(nameof(JsonElement.GetProperty), new[] { typeof(string) })!; var propertyElement = Expression.Call(elementParam, getPropertyMethod, Expression.Constant(propName)); var deserializeMethod = typeof(JsonSerializer).GetMethod(nameof(JsonSerializer.Deserialize), new[] { typeof(JsonElement), typeof(Type), typeof(JsonSerializerOptions) })!; var valueExpression = Expression.Call(deserializeMethod, propertyElement, Expression.Constant(prop.PropertyType), optionsParam); arguments.Add(Expression.Convert(valueExpression, prop.PropertyType)); } var newExpression = Expression.New(ctor, arguments); return Expression.Lambda<Func<JsonElement, JsonSerializerOptions, T>>(newExpression, elementParam, optionsParam).Compile(); } } }
使用方式
在Json序列化配置中注册转换器工厂即可:
var jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Converters = { new ValueObjectConverterFactory() } };
性能说明
本实现采用表达式树预编译序列化/反序列化逻辑,每个值对象类型仅在第一次使用时执行一次反射和编译,后续调用直接执行编译后的委托,性能与原生System.Text.Json序列化接近,无额外运行时反射开销。
内容的提问来源于stack exchange,提问作者rebornx
相关产品推荐
相关产品推荐

