1

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

Paul
  • 2,591
  • 6
  • 33
  • 65
  • Does this answer your question? [How to set json serializer settings in asp.net core 3?](https://stackoverflow.com/questions/58392039/how-to-set-json-serializer-settings-in-asp-net-core-3) – Ben Cottrell Jul 17 '21 at 12:12

2 Answers2

3

Adapted from Add JSON Options In HTTP Triggered Azure Functions

Prerequisites

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.

Code

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.

stuartd
  • 66,195
  • 14
  • 128
  • 158
0

The accepted answer for this question does not work for Azure Functions v3+. You can use version 3.0+ of Microsoft.AspNetCore.Mvc.NewtonsoftJson package to setup the JSON serializer options.

See: https://stackoverflow.com/a/62270924/5436889

Mo Nazemi
  • 2,496
  • 2
  • 14
  • 22