Does the new `System.Text.Json` have a required property attribute?

若如初见. 提交于 2019-12-11 10:56:15

问题


I've combed through the MS docs but cannot find an attribute equivalent to the NewtonSoft JsonPropertyRequired.

What I'm looking for this:

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

Am I just missing something or does this level of validation not exist in the Microsoft library?


回答1:


Not as of .NET core 3.0. The only ones supported are:

JsonConverterAttribute
JsonExtensionDataAttribute
JsonIgnoreAttribute
JsonPropertyNameAttribute

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
    }
}


来源:https://stackoverflow.com/questions/58443181/does-the-new-system-text-json-have-a-required-property-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!