如何在.NET Core 6的System.Text.Json中无特性排除Func类型属性序列化
排除所有Func类型属性的System.Text.Json序列化方案
在.NET Core 6的System.Text.Json环境下,无需添加[JsonIgnore]或其他特性,即可全局排除所有Func
1. 自定义类型信息修饰器
创建一个方法,用于修改序列化时的类型元数据,直接移除所有Func系列委托类型的属性:
private static void RemoveFuncProperties(JsonTypeInfo typeInfo) { if (typeInfo.Kind != JsonTypeInfoKind.Object) return; // 倒序遍历属性列表,避免移除元素时索引错乱 for (int i = typeInfo.Properties.Count - 1; i >= 0; i--) { var propertyType = typeInfo.Properties[i].PropertyType; // 判断属性类型是否为Func系列委托:检查是否继承自Delegate,且名称以Func`开头(泛型Func的命名格式为Func`1、Func`2等) if (propertyType.IsAssignableTo(typeof(Delegate)) && propertyType.Name.StartsWith("Func`")) { typeInfo.Properties.RemoveAt(i); } } }
2. 配置JsonSerializerOptions
将上述修饰器注入到DefaultJsonTypeInfoResolver中,生成自定义的序列化配置:
var jsonOptions = new JsonSerializerOptions { TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { RemoveFuncProperties } } };
使用该配置进行序列化时,所有Func类型的属性会被自动排除:
var foo = new Foo { DoCalculation = () => 42, Bar = "Hello World" }; // 序列化结果仅包含Bar属性:{"Bar":"Hello World"} string serializedJson = JsonSerializer.Serialize(foo, jsonOptions);
3. ASP.NET Core全局配置
如果是在ASP.NET Core项目中,想要让所有API接口的序列化都应用该规则,可在Program.cs中全局配置:
builder.Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { RemoveFuncProperties } }; });
内容的提问来源于stack exchange,提问作者THX-1138
相关产品推荐
相关产品推荐

