user610217
user610217

Reputation:

JSON.NET NullValueHandling in JsonPropertyAttribute not working as expected

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

Answers (4)

Ebram
Ebram

Reputation: 1102

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; }
}

Upvotes: 8

Reza Ahmadi
Reza Ahmadi

Reputation: 65

add this service on Startup.cs :

services.AddControllersWithViews().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.IgnoreNullValues = true;
});

Upvotes: 1

Kush
Kush

Reputation: 438

You may use [JsonProperty(NullValueHandling=NullValueHandling.Ignore)] instead

Upvotes: 1

Manoj Gupta
Manoj Gupta

Reputation: 1

Try passing new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore } as third parameter in JsonConvert.SerializeObject method.

Upvotes: 0

Related Questions