0

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

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

I've deleted the previous comment because it turns out I'm an idiot... my example I'm using 0 for simplicity... but then I notice the actual code is using decimal.MinValue as the default value (which is, guess what, -79228162514264337593543950335). So thank you, this is great

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.