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?
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.
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.
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);
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.
Because Decimal is a non-nullable type so you cannot do that.
You need Decimal?
to bind null
value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With