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

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

What I’m looking for is 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?

Answer

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

JsonConverterAttribute
JsonExtensionDataAttribute
JsonIgnoreAttribute
JsonPropertyNameAttribute

Update: In .NET 5.0 RC1 the set is

JsonConstructorAttribute
JsonConverterAttribute
JsonExtensionDataAttribute
JsonIgnoreAttribute
JsonIncludeAttribute
JsonNumberHandlingAttribute
JsonPropertyNameAttribute

Unfortunately even a custom converter won’t work because null values skip calling Read and Write methods (tested in 3.0)

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

Leave a Reply

Your email address will not be published. Required fields are marked *