Reputation:
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?
Upvotes: 10
Views: 8799
Reputation: 1102
The default text serializer used by .net API is System.Text.Json:
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; }
}
Upvotes: 8
Reputation: 65
add this service on Startup.cs
:
services.AddControllersWithViews().AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
Upvotes: 1
Reputation: 438
You may use [JsonProperty(NullValueHandling=NullValueHandling.Ignore)] instead
Upvotes: 1
Reputation: 1
Try passing new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }
as third parameter in JsonConvert.SerializeObject method.
Upvotes: 0