Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

348
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda