freefaller
freefaller

Reputation: 19963

Default numeric value from JSON property with empty string

I'm trying to deserialize a JSON string, which contains an empty string value for one property... that property should be parsed into a decimal property of the class...

public class myClass {
  public decimal my_value { get; set; } = 0;
}
var json = "{ \"my_value\": \"\" }";
var data = JsonConvert.DeserializeObject<myClass>(json);

The issue is that data is coming back as a null object.

I've tried setting the property to be decimal?, and that does return an object, but my_value is null when I need it to default to 0.

I've also tried the following, but it returns a null object (using either decimal or decimal?)...

  [System.ComponentModel.DefaultValue(0)]
  [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
  public decimal my_value { get; set; } = 0;

How can I set this up to default to a value of 0 if the JSON contains an empty string for the property?

Before anybody states it... yes, the easy answer is to not have an empty string property in the JSON, but there is nothing I can do about it

Upvotes: 0

Views: 1834

Answers (1)

ejwill
ejwill

Reputation: 170

You need to set up your serialization settings to ignore null values.

the settings would look like this if you are using Newtonsoft. You can learn more here

var = jsonSettings = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
}

Upvotes: 2

Related Questions