10

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?

2
  • Have you solved this? Running into same problem, the attribute on the property has no effect. Commented Aug 23, 2015 at 16:10
  • In my case, the serialization of that object was overriden with a custom CustomCreationConverter, but you could also see this: stackoverflow.com/questions/8424151/… Commented Aug 23, 2015 at 18:20

4 Answers 4

8

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

3 Comments

This question is 7 years old; at the time it was asked, JSON.NET was the de facto JSON serializer.
This i not an answer to the question which was asked.
This might not have been an answer when the question was asked, but it certainly helped me out just now :)
1

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

Comments

1

add this service on Startup.cs :

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

Comments

0

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

1 Comment

Hmmm... there are quite a few properties that I do want to render as null though, and I think that will apply a blanket policy for the entire serialization.

Your Answer

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