Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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>();

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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

}
over 4 years ago · Santiago Trujillo Denunciar

0

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; }
}
    
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda