I have a webapi that receives a JSON through a POST. Sometimes one double value might arrive with null, so something like this
class A
{
public double val {get; set;}
}
Then the incoming json might be { "val": null }
I get a parsing error because null cannot be applied to double. In past days I would have added this
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
from the Newtonsoft library. However I'm using System.Text.Json nowadays. Is there something similar? I didn't find anything. At one place I use this here
[System.Text.Json.Serialization.JsonConverter(typeof(MyJsonConverter))]
But that seems to be an overkill for a single double value.
Btw: If possible I would like to avoid setting the double nullable, or else I would have to use .GetValueOrDefault()
at multiple places, which looks ugly
CodePudding user response:
Since the data you load can provide a nullable value, it does make sense to set the property type to double?
. You could work around GetValueOrDefault()
by modifying the getter to return a default straight away whenever the value is null
.
This question might be a duplicate; however, I cannot mark it as such due to low rep. Here is a similar question I've found: How to deal with nullable reference types with System.Text.Json?
Here are other links I've found:
- https://www.conradakunga.com/blog/handling-null-and-empty-strings-with-system-text-json/
- https://docs.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.ignorenullvalues?view=net-6.0
CodePudding user response:
Well, I'm afraid that it's not exactly possible the way you want it.
Possible options -
Make your property nullable itself [should be done ideally].
- Which you already deferred doing.
Use IgnoreNullValues option in the JSON serializer options:
services.AddControllers() .AddJsonOptions(x=> { x.JsonSerializerOptions.IgnoreNullValues = true; });
- The downside of this option however is that it will also remove null properties (i.e.their names) from response text during serialization. Which, I suppose you want to do for your client/UI applications.
In my opinion, you should not be allowing your API to accept values that the property doesn't accept (e.g. null for double type property).
Therefore, you would need to either change the property to nullable or have a custom converter to handle your specific scenario.
CodePudding user response:
just make your property nullable, and make another problem for you somewhere else in your code, if you don't want to use a bugless serializer
public double? val {get; set;}
or try this workaround
[JsonPropertyName("val")]
public double? _value { private get; set; }
public double Val
{
get { return _value == null ? 0 : (double)_value; }
set { _value = value; }
}