I have a request class which has the following property
/// <summary>
/// First time discount flag
/// </summary>
[JsonProperty("firstTimeDiscountFlag")]
public string FirstTimeDiscountFlag { get; set; }
I am doing this to check if it is null and has allowed values
if(string.IsNullOrWhiteSpace(request.FirstTimeDiscountFlag)
|| (request.FirstTimeDiscountFlag.ToUpper() != "Y" && request.FirstTimeDiscountFlag.ToUpper() != "N"))
Is there a better way to handle this?
2
Answers
You could write this as an expression bodied property like this…
But a better approach might be to investigate the Fluent Validation library (https://github.com/FluentValidation/FluentValidation) and write a validator for you model class.
The proper approach is to use a
JsonConverter
that will serialize a boolean toY
orN
and handle the deserialization too:You use it via the
JsonConverterAttribute
:Working demo available here.