21

我已经梳理了MS 文档,但找不到与NewtonSoft JsonPropertyRequired等效的属性。

我正在寻找的是这个:

public class Videogame
{
    [JsonProperty(Required = Required.Always)]
    public string Name { get; set; }
}

我只是遗漏了什么,还是 Microsoft 库中不存在这种级别的验证?

4

4 回答 4

10

不是.NET Core 3.0。唯一支持的是:

JsonConverterAttribute
JsonExtensionDataAttribute
JsonIgnoreAttribute
JsonPropertyNameAttribute

更新:在.NET 5.0中,该集合是

JsonConstructorAttribute
JsonConverterAttribute
JsonExtensionDataAttribute
JsonIgnoreAttribute
JsonIncludeAttribute
JsonNumberHandlingAttribute
JsonPropertyNameAttribute

不幸的是,即使是HandleNull => true如何为 .NET 中的 JSON 序列化(编组)编写自定义转换器中显示的自定义转换器也不起作用,因为如果不存在读取和写入方法中的属性不被调用(在 5.0 中测试,并且在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
于 2019-10-18T04:06:42.730 回答
7

请尝试我作为 System.Text.Json 的扩展编写的这个库,以提供缺少的功能:https ://github.com/dahomey-technologies/Dahomey.Json 。

您将找到对 JsonRequiredAttribute 的支持。

public class Videogame
{
    [JsonRequired(RequirementPolicy.Always)]
    public string Name { get; set; }
}

通过调用命名空间 Dahomey.Json 中定义的扩展方法 SetupExtensions 来设置 json 扩展。然后使用常规的 Sytem.Text.Json API 反序列化您的类。

JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();

const string json = @"{""Name"":""BGE2""}";
Videogame obj = JsonSerializer.Deserialize<Videogame>(json, options);
于 2019-12-11T20:51:48.167 回答
6

5.0开始,您可以使用构造函数来实现这一点。反序列化期间任何异常都会冒泡。

public class Videogame
{
    public Videogame(string name, int? year)
    {
        this.Name = name ?? throw new ArgumentNullException(nameof(name));
        this.Year = year ?? throw new ArgumentNullException(nameof(year));
    }

    public string Name { get; }

    [NotNull]
    public int? Year { get; }
}

注意 如果 JSON 中缺少构造函数参数,该库不会抛出错误。它只是使用类型的默认值(所以0for int)。如果要处理这种情况,最好使用可为空的值类型。

此外,构造函数参数的类型必须与您的字段/属性完全匹配,因此不幸的是,不要使用 from int?to 。int我找到了分析属性[NotNull]和/或[DisallowNulls]减少了不便。

于 2021-03-11T02:16:14.173 回答
-2

我正在[Required]使用System.ComponentModel.DataAnnotations. 我已经将它与Newtonsoft.Json和一起使用System.Text.Json

于 2020-01-15T11:37:46.957 回答