新的"System.Text.Json"是否具有必需的属性属性? [英] Does the new `System.Text.Json` have a required property attribute?

查看:150
本文介绍了新的"System.Text.Json"是否具有必需的属性属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过 NewtonSoft JsonPropertyRequired .

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?

推荐答案

不幸的是,即使自定义转换器也不起作用,因为null值会跳过对Read和Write方法的调用.

Unfortunately even a custom converter won't work because null values skip calling Read and Write methods.

public class Radiokiller
{
   [JsonConverter(typeof(MyCustomNotNullConverter<string>))] 
   public string Name { get; set; }  
}

public class MyCustomNotNullConverter<T> : JsonConverter<T>
{
    public override bool CanConvert(Type typeToConvert) => true;

    public override T Read(...)
    {
        //Not called for nulls
    }

    public override void Write(...)
    {
        // Not called for nulls
    }
}

这篇关于新的"System.Text.Json"是否具有必需的属性属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆