Home > Back-end >  JsonConvert.DeserializeObject defaults nullable int to 0
JsonConvert.DeserializeObject defaults nullable int to 0

Time:10-21

Hello I have the following code, JsonConvert.DeserializeObject default the missing int to 0 even tho it's nullable. How can I have null for age?

class Person
{
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public string Name { get;  set; }

    [DataMember]
    [Range(0, 100, ErrorMessage = "Age should be between 0 and 100")]
    public int? Age { get;  set; }
}
public class HelloWorld
{

    public static void Main(string[] args)
    {
        string json = "{\"name\":\"mmmm\"}";
        Person person = JsonConvert.DeserializeObject<Person>(json);
        Console.WriteLine("Hello World "   person.Age);
    }
}

CodePudding user response:

It is because you have a constructor that gets age as int and not int?. You should change it as follows:

public Person(string name, int? age)
{
    Name = name;
    Age = age;
}
  • Related