在项目设置中具有<nullable>enabled</nullable>,具有以下类
<nullable>enabled</nullable>
public class Car{ public required string Name { get; init; }}
public class Car
{
public required string Name { get; init; }
}
并将其从string反序列化:
System.Text.Json.JsonSerializer.Deserialize<Car>("""{"Name": null}""");
不引发异常由于属性被标记为不可为空,是否可以将STJ配置为在null值的情况下引发?
null
lpwwtiir1#
由于您使用的是.NET 7和C# 11,因此可以尝试使用System.Text.Json包中的JsonRequiredAttribute。或者,在Newtonsoft.Json包中有一个类似的选项。
public class Car{ [JsonProperty(Required = Required.Always)] public string Name { get; init; }}
[JsonProperty(Required = Required.Always)]
public string Name { get; init; }
1条答案
按热度按时间lpwwtiir1#
由于您使用的是.NET 7和C# 11,因此可以尝试使用System.Text.Json包中的JsonRequiredAttribute。
或者,在Newtonsoft.Json包中有一个类似的选项。