How to provide the Default value to a boolean property when it was null

Viewed 899

In the below code i am getting an exception because "isValid" is coming as null from the input request.

I want to set "isValid" to "False" when it was null from the input request.

Can anyone pls suggest me how i can do this ?

public class Details
{
    public string status { get; set; }
    public MessageInfo messageInfo { get; set; }
}

public class MessageInfo
{
    public bool isValid { get; set; }
}

var inputMessage =
{
    "Body":
    {
     "status":"success",
     "MessageInfo": 
      {
        "isValid":null
      }
    }
}

var messagebody = inputMessage.Body.ToObject<Details>();

2 Answers

Assuming you are using Newtonsoft.Json, use the NullValueHandling property of the JsonSerializer class, setting it to ignore. Then pass in this instance of JsonSerializer to an overload of the ToObject<T> function.

This tells serialization to ignore any properties that were null, leaving the property initialized to its default value. (You can control that default value separately via System.ComponentModel.DefaultValueAttribute if you want.)

Fully compiling example below. (The references to 'Body' were removed, to make it easier to focus on the main problem.)

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace SomeNamespace
{
    public class Program
    {
        private static void Main()
        {
            var inputMessage = JToken.Parse(
            @"{
                ""status"":""success"",
                ""MessageInfo"": 
                {
                    ""isValid"":null
                }
            }");
            
            // build a custom serializer with a setting to ignore null
            var jsonSettings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
            };
            var serializer = JsonSerializer.Create(jsonSettings);

            // using the serializer with custom settings avoids the original exception
            var messagebody = inputMessage.ToObject<Details>(serializer);
        }
    }

    public class Details
    {
        public string status { get; set; }
        public MessageInfo messageInfo { get; set; }
    }

    public class MessageInfo
    {
        public bool isValid { get; set; }
    }

}

this works for me

void Main()
{
    var inputMessage = "{ \"Body\":{\"status\":\"success\", \"MessageInfo\":{\"isValid\":null} }}";

   var inputMessageObj= JsonConvert.DeserializeObject<Root>(inputMessage);
}

classes

public class Details
{
    public string status { get; set; }
    public MessageInfo messageInfo { get; set; }
}


public class MessageInfo
{

    private bool? _isValid = false;
    public bool? IsValid
    {
        get { return _isValid; }
        set { _isValid = value == null ? false : value; }
    }
}

    public class Body
    {
        public string Status { get; set; }
        public MessageInfo MessageInfo { get; set; }
    }

public class Root
{
    public Body Body { get; set; }
}
    
Related