I have managed to ignore the null buts but I have not been able to do the same with the empty strings. My project is an Azure Function running on .NET Core 3.1.
The configuration I have is the following in the startup
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Text.Json.Serialization;
builder.Services.AddMvcCore()
.AddNewtonsoftJson(options =>
{
options.UseMemberCasing();
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
options.SerializerSettings.Formatting = Formatting.Indented;
options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
})
.AddJsonOptions(option =>
{
option.JsonSerializerOptions.IgnoreNullValues = true;
option.JsonSerializerOptions.WriteIndented = true;
option.JsonSerializerOptions.IgnoreReadOnlyProperties = true;
});
Any idea why I don’t ignore empty strings?
3
Answers
The model that I am waiting for is the following
But I should ignore the
Your settings seems to be correct.
However you might need to decorate your properties with the Default value attribute for DefaultValueHandling.Ignore to kick in
Below is a working sample
Output : planetName property is ignored while serializing
EDIT :
Tried to implement AZ function app with a startup file and added settings for serialization. But I found that adding newtonsoft serializer settings to builder services has no effect on serialization.
Best workaround would be to add settings to function while serializing like below example from AZ function that i tried out.
Input :
Output :
Maybe override the tostring method and pass in your JSON options there or just do some isnullorempty checks before you jsonStringify.
or use