Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required number parameter defaulting to 0 when not included in JSON

I have a model where I am using DataAnnotations to perform validation, such as

public class OrderDTO
{
    [Required]
    public int Id { get; set; }

    [Required]
    public Decimal Amount { get; set; }
}

Then I am checking the ModelState in each request to make sure that the JSON is valid.

However, I am having trouble for number properties such as Amount above. Even though it is set as [Required], if it's not included in the JSON it will skip the ModelState validation because it is automatically defaulted to 0 instead of null, so the model will seem valid even though it isn't.

An easy way to 'fix' this is to set all the number properties as nullable (int?, Decimal?). If I do this, the defaulting to 0 doesn't happen, but I don't like this as a definitive solution as I need to change my model.

Is there a way to set the properties to null if they are not part of the JSON?

like image 529
Antrim Avatar asked Jan 14 '16 09:01

Antrim


People also ask

What does a leading 0 indicate in a JSON string?

A leading 0 indicates an octal number in JavaScript. An octal number cannot contain an 8; therefore, that number is invalid. Moreover, JSON doesn't (officially) support octal numbers, so formally the JSON is invalid, even if the number would not contain an 8. Some parsers do support it though, which may lead to some confusion.

Can JSON accept an integer that begins with 0?

If I update the JSON by either removing the 0 from "UPC":083456789012, or converting it to "UPC":"083456789012", it becomes valid. Can JSON really not accept an integer that begins with 0, or is there a way around the problem? JSON syntax doesn't allow numbers to start with the digit 0. You can of course put your numbers in quotes.

How to ignore all null-value properties when serializing a JSON string?

To ignore all null-value properties when serializing, set the IgnoreNullValues property to true, as shown in the following example: C#. Copy. var options = new JsonSerializerOptions { IgnoreNullValues = true , WriteIndented = true }; jsonString = JsonSerializer.Serialize (weatherForecast, options);

How do I ignore individual properties in JSON output?

To ignore individual properties, use the [JsonIgnore] attribute. Here's an example type to serialize and JSON output: You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.


1 Answers

Because Decimal is a non-nullable type so you cannot do that. You need Decimal? to bind null value.

like image 187
tdat00 Avatar answered Oct 27 '22 01:10

tdat00