8

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?

Jeremy Holovacs
  • 22,480
  • 33
  • 117
  • 254
  • Have you solved this? Running into same problem, the attribute on the property has no effect. – Jacek Gorgoń Aug 23 '15 at 16:10
  • In my case, the serialization of that object was overriden with a custom `CustomCreationConverter`, but you could also see this: http://stackoverflow.com/questions/8424151/json-net-serializer-ignoring-jsonproperty?rq=1 – Jacek Gorgoń Aug 23 '15 at 18:20

4 Answers4

4

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; }
}
Ebram
  • 1,042
  • 1
  • 13
  • 26
1

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

Kush
  • 438
  • 1
  • 7
  • 20
1

add this service on Startup.cs :

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

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

  • 1
    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. – Jeremy Holovacs Mar 23 '15 at 19:26