新的`System.Text.Json` 是否有必需的属性属性? [英] Does the new `System.Text.Json` have a required property attribute?
问题描述
我已经梳理了 MS 文档 但找不到与 NewtonSoft JsonPropertyRequired<等效的属性/a>.
I've combed through the MS docs but cannot find an attribute equivalent to the NewtonSoft JsonPropertyRequired.
我要找的是这个:
public class Videogame
{
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
}
我是否只是遗漏了某些东西,或者 Microsoft 库中不存在这种级别的验证?
Am I just missing something or does this level of validation not exist in the Microsoft library?
推荐答案
Not as of .NET Core 3.0.唯一支持的是:
Not as of .NET Core 3.0. The only ones supported are:
JsonConverterAttribute
JsonExtensionDataAttribute
JsonIgnoreAttribute
JsonPropertyNameAttribute
更新:在 .NET 5.0 集是
JsonConstructorAttribute
JsonConverterAttribute
JsonExtensionDataAttribute
JsonIgnoreAttribute
JsonIncludeAttribute
JsonNumberHandlingAttribute
JsonPropertyNameAttribute
不幸的是,即使是带有 HandleNull => 的自定义转换器.true
显示在 如何在 .NET 中为 JSON 序列化(编组)编写自定义转换器 将不起作用,因为如果属性不存在,则读取和写入方法不是调用(5.0 测试,3.0 修改版)
Unfortunately even a custom converter with HandleNull => true
shown in How to write custom converters for JSON serialization (marshalling) in .NET won't work because if the property in not present Read and Write methods are not called (tested in 5.0, and a modified version in 3.0)
public class Radiokiller
{
[JsonConverter(typeof(MyCustomNotNullConverter))]
public string Name { get; set; }
}
public class MyCustomNotNullConverter : JsonConverter<string>
{
public override bool HandleNull => true;
public override string Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) =>
reader.GetString() ?? throw new Exception("Value required.");
public override void Write(
Utf8JsonWriter writer,
string value,
JsonSerializerOptions options) =>
writer.WriteStringValue(value);
}
var json = "{}";
var o = JsonSerializer.Deserialize<Radiokiller>(json); // no exception :(
json = "{ "Name" : null}";
o = JsonSerializer.Deserialize<Radiokiller>(json); // throws
这篇关于新的`System.Text.Json` 是否有必需的属性属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!