Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore property when null using the new Net Core 3.0 Json

When using JSON.Net in ASP.Net Core 2.2 I was able to ignore a property when its value was null when serializing to JSON:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public DateTime? Created { get; set; } 

But when using the new ASP.Net Core 3.0 built in JSON (System.Text.Json) I can’t find an equivalent attribute to ignore a property if its value is null.

I could only find JsonIgnore.

Am I missing something?

like image 220
Miguel Moura Avatar asked Sep 25 '19 21:09

Miguel Moura


People also ask

How do I ignore properties in JSON?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

Can JSON include null?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

Is Newtonsoft JSON still supported?

Yet Newtonsoft. Json was basically scrapped by Microsoft with the coming of . NET Core 3.0 in favor of its newer offering designed for better performance, System.


1 Answers

I'm looking at .Net Core 3.1, where this should ignore null values

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

Note, the above isn't per property/attribute, although there is an attribute which may be helpful JsonIgnoreAttribute

An alternative, to solve your problem might be a JsonConverterAttribute, information on how to write your own converter is here

like image 160
0909EM Avatar answered Sep 20 '22 20:09

0909EM