skip to Main Content

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


  1. You could write this as an expression bodied property like this…

    public string FirstTimeDiscountFlag { get; set; }
        
    public bool IsFirstTimeDiscountFlagValid => 
        string.IsNullOrEmpty(FirstTimeDiscountFlag) || "YN".Contains(FirstTimeDiscountFlag.ToUpper());
    

    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.

    Login or Signup to reply.
  2. The proper approach is to use a JsonConverter that will serialize a boolean to Y or N and handle the deserialization too:

    public class YNBoolConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        {
            writer.WriteValue(value switch
            {
                true => "Y",
                false => "N",
                _ => string.Empty
            });
        }
    
        public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
        {
            return reader.Value switch
            {
                true => true,
                "Y" => true,
                "y" => true,
    
                false => false,
                "N" => false,
                "n" => false,
    
                _ => existingValue
            };
        }
    
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(string);
        }
    }
    

    You use it via the JsonConverterAttribute:

    {
        [JsonConverter(typeof(YNBoolConverter))]
        public bool? BoolValue { get; set; }
    }
    

    Working demo available here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search