I have a class like so:
[JsonObject]
public class Condition
{
[JsonProperty(PropertyName = "_id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "expressions", NullValueHandling = NullValueHandling.Ignore)]
public IEnumerable<Expression> Expressions { get; set; }
[JsonProperty(PropertyName = "logical_operation")]
[JsonConverter(typeof(StringEnumConverter))]
public LogicOp? LogicalOperation { get; set; }
[JsonProperty(PropertyName = "_type")]
[JsonConverter(typeof(AssessmentExpressionTypeConverter))]
public ExpressionType Type { get; set; }
}
However, when the Expressions property is null, and I serialize the object like so:
var serialized = JsonConvert.SerializeObject(condition, Formatting.Indented);
... the text of the Json string has the line:
"expressions": null
My understanding is that this should not happen. What am I doing wrong?
The default text serializer used by .net API is System.Text.Json:
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-customize-properties?pivots=dotnet-6-0
So if you want to ignore if null you can use:
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
Example:
public class Forecast
{
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public DateTime Date { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public int TemperatureC { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Summary { get; set; }
}
You may use [JsonProperty(NullValueHandling=NullValueHandling.Ignore)] instead
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