Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JsonConvert.DeserializeObject defaults nullable int to 0

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading