Lee*_*lla 9 c# json.net .net-core-3.1 system.text.json asp.net-core-3.1
使用 Newtonsoft 我们有一个自定义解析器来忽略空集合。.Net core 3.1 中的新 system.text.json 是否有任何等效配置
TypeInfoResolver.NET 7 中添加的(可通过 system.text.json nuget 包在较旧的运行时访问,截至本答案时预发布)允许这样做。
例子:
using System.Collections;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
public class TestObject {
public List<int> Ints { get; } = new() {3, 4, 5};
public List<int> EmptyInts { get; } = new();
public List<int> NullInts { get; }
}
public static class Program {
public static void Main() {
var options = new JsonSerializerOptions {
TypeInfoResolver = new DefaultJsonTypeInfoResolver {
Modifiers = {DefaultValueModifier}
},
};
var obj = new TestObject();
var text = JsonSerializer.Serialize(obj, options);
Console.WriteLine(text);
}
private static void DefaultValueModifier(JsonTypeInfo type_info) {
foreach (var property in type_info.Properties) {
if (typeof(ICollection).IsAssignableFrom(property.PropertyType)) {
property.ShouldSerialize = (_, val) => val is ICollection collection && collection.Count > 0;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
{"Ints":[3,4,5]}
Run Code Online (Sandbox Code Playgroud)
有条件地忽略.NET5 官方How to migrate from Newtonsoft.Json to System.Text.Json from 2020 Dec 14 中的属性:
System.Text.Json 提供了以下方法来在序列化时忽略属性或字段:
- [JsonIgnore] 属性 (...)。
- IgnoreReadOnlyProperties 全局选项 (...)。
- (...) JsonSerializerOptions.IgnoreReadOnlyFields 全局 (...)
- DefaultIgnoreCondition 全局选项允许您忽略具有默认值的所有值类型属性,或忽略具有 null 值的所有引用类型属性。
这些选项不允许您:
- 忽略基于运行时评估的任意标准选择的属性。
对于该功能,您可以编写一个自定义转换器。下面是一个示例 POCO 和一个自定义转换器,说明了这种方法:
(下面是类型的自定义转换器的示例)
请注意,此转换器需要是包含集合属性的类型的转换器,它不是集合类型的转换器(请参阅我的第二个答案)。