如何配置System.Text.Json对非可空属性的null值抛出异常?
配置System.Text.Json在非可空属性遇null时抛出异常
项目已启用<nullable>enabled</nullable>,定义如下Car类:
public class Car { public required string Name { get; init; } }
执行以下反序列化代码时:
System.Text.Json.JsonSerializer.Deserialize<Car>("""{"Name": null}""");
程序并未抛出异常,但Name是标记为非可空的属性。可以通过配置System.Text.Json(STJ)让这种场景抛出异常,具体实现分版本处理:
.NET 7及以上版本
直接使用STJ新增的ThrowOnNullReferenceValues配置项,将其设为true即可:
var options = new JsonSerializerOptions { ThrowOnNullReferenceValues = true }; var car = JsonSerializer.Deserialize<Car>("""{"Name": null}""", options);
执行后会抛出JsonException,提示无法将null赋值给非可空引用类型属性Name。
.NET 6版本
由于.NET 7才引入ThrowOnNullReferenceValues,.NET 6需要通过自定义类型信息解析器来实现:
var options = new JsonSerializerOptions { TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { typeInfo => { if (typeInfo.Kind != JsonTypeInfoKind.Object) return; foreach (var property in typeInfo.Properties) { // 识别非可空引用类型属性(排除值类型和可空值类型) var propertyType = property.PropertyType; if (!propertyType.IsValueType && Nullable.GetUnderlyingType(propertyType) == null) { var originalSetter = property.Set; property.Set = (obj, value) => { if (value == null) { throw new JsonException($"属性 '{property.Name}' 不能为null"); } originalSetter(obj, value); }; } } } } } }; var car = JsonSerializer.Deserialize<Car>("""{"Name": null}""", options);
这段代码通过包装属性的赋值方法,在检测到null值时手动抛出异常,达到预期效果。
内容的提问来源于stack exchange,提问作者user963935
相关产品推荐
相关产品推荐

