使用System.Text.Json将集合反序列化为空列表而非null
解决System.Text.Json反序列化时集合属性为null的问题
当使用System.Text.Json反序列化时,集合属性若没有对应值会被设为null,避免空值检查的方案有以下几种:
1. 类内直接初始化集合属性(最推荐)
在定义类的时候,直接给集合属性初始化一个空实例,不管是通过属性初始化器还是构造函数,这样反序列化时即使没有对应值,属性也会保持空集合而非null:
public class Product { // 属性初始化器方式 public List<string> Tags { get; set; } = new List<string>(); // 构造函数方式(适合需要更复杂初始化逻辑的场景) public Product() { Tags = new List<string>(); } }
这种方式无需额外配置序列化选项,代码直观且维护成本低。
2. 自定义Json转换器
如果无法修改类的定义,可以自定义转换器,让反序列化时将null的集合转为空集合:
public class EmptyListConverter<T> : JsonConverter<List<T>> { public override List<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) { return new List<T>(); } return JsonSerializer.Deserialize<List<T>>(ref reader, options) ?? new List<T>(); } public override void Write(Utf8JsonWriter writer, List<T> value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value, options); } }
注册转换器并使用:
var options = new JsonSerializerOptions(); options.Converters.Add(new EmptyListConverter<string>()); // 反序列化示例 var product = JsonSerializer.Deserialize<Product>(jsonString, options);
如果需要全局适配所有List<T>类型,.NET 6及以上支持注册开放泛型转换器:
options.Converters.Add(typeof(EmptyListConverter<>));
3. .NET 7+ 元数据配置
在.NET 7及更高版本中,可以通过修改JsonTypeInfo的方式全局配置,自动将null集合转为空实例:
var options = new JsonSerializerOptions(); options.TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { typeInfo => { if (typeInfo.Kind != JsonTypeInfoKind.Object) return; foreach (var property in typeInfo.Properties) { // 针对List<T>类型处理 if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(List<>)) { var originalSetter = property.SetValue; property.SetValue = (obj, value) => { // 如果值为null,创建空集合实例 originalSetter(obj, value ?? Activator.CreateInstance(property.PropertyType)); }; } } } } };
内容的提问来源于stack exchange,提问作者SuperJMN
相关产品推荐
相关产品推荐

