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?
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.
JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With