-1

I have in my class:

public class submitRequest
{
    public int students { get; set; } = 0;

When I send from frontend to backend a non-number (e.g. null, or empty string), it does not use default value and I get:

"The JSON value could not be converted to System.Int32. Path: $.students"

But when I only have

 public int students { get; } = 0;

it works fine. But then I have problems that correct values (1, 2, ...) sent from frontend are ignored, and the value of students is always 0.

farahm
  • 1,326
  • 6
  • 32
  • 70
  • 1
    Could you add a minimal example of the JSON and the code needed to reproduce the problem to the question? – Andrew Morton Jul 08 '23 at 17:04
  • Does this answer your question? [Newtonsoft how to deserialize null to default value again after switching to .Net Core](https://stackoverflow.com/questions/71588334/newtonsoft-how-to-deserialize-null-to-default-value-again-after-switching-to-ne) – GSerg Jul 08 '23 at 17:11

1 Answers1

3

The reason why the default value is not used when you send a non-number value from the frontend is because the deserialization process fails and an exception is thrown.

To handle this situation, you can make the students property nullable by changing its type to int?:

public class SubmitRequest
{
    public int? Students { get; set; }
}

By making the property nullable, the deserialization process will succeed even if the JSON value is null or not a valid integer.

If the JSON value is null, the property will be set to null. If the JSON value is not a valid integer, the property will be set to null as well.

user366312
  • 16,949
  • 65
  • 235
  • 452
  • 1
    This hit me a few years ago, too. Deserialization does not use default property values! The other option is to specify the default value in your JSON instead of in the api. – ps2goat Jul 08 '23 at 18:14