How can I setup the serializer in Azure Functions to ignore nulls when serializing?
This is a v3 function
I have tried
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
};
In the startup for my function
I am now starting to think that Newtonsoft isnt being used for json
How can I force Newtonsoft to be used?
Cheers
Paul
The various function (and MVC) versions have different ways of setting this up and may use Newtonsoft.Json or System.Text.Json
Links:
https://github.com/Azure/azure-functions-host/issues/5841#issuecomment-987168758
https://stackoverflow.com/a/62270924/5436889
test
Adapted from Add JSON Options In HTTP Triggered Azure Functions
You need ensure that all prerequisites are fulfilled as mentioned here
From that docs page:
Before you can use dependency injection, you must install the following NuGet packages:
- Microsoft.Azure.Functions.Extensions
- Microsoft.NET.Sdk.Functions package version 1.0.28 or later
- Microsoft.Extensions.DependencyInjection (currently, only version 3.x and earlier supported)
Note:
The guidance in this article applies only to C# class library functions, which run in-process with the runtime. This custom dependency injection model doesn't apply to .NET isolated functions, which lets you run .NET 5.0 functions out-of-process. The .NET isolated process model relies on regular ASP.NET Core dependency injection patterns.
Add Startup class to your Azure Function Project as given below:
using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]
namespace MyNamespace {
public class Startup: FunctionsStartup {
public override void Configure(IFunctionsHostBuilder builder) {
builder.Services.AddMvcCore().AddJsonFormatters().AddJsonOptions(options => {
// Adding json option to ignore null values.
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
}
}
}
This will set the JSON option to ignore null values.