问题
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