访问 Json 序列化程序选项以避免在 Azure Functions v3 中序列化 null

Access Json Serializer options to avoid serializing null in Azure Functions v3

如何在 Azure Functions 中设置序列化程序以在序列化时忽略空值?

这是 v3 函数

我试过了

        JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            NullValueHandling = NullValueHandling.Ignore
        };

在我的函数的启动中

我现在开始认为 Newtonsoft 没有被用于 json

如何强制使用 Newtonsoft?

干杯

保罗

改编自Add JSON Options In HTTP Triggered Azure Functions

先决条件

You need ensure that all prerequisites are fulfilled as mentioned here

来自该文档页面:

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)

注:

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.

代码

将 Startup class 添加到您的 Azure Function 项目,如下所示:

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.

此问题的公认答案不适用于 Azure Functions v3+。 您可以使用 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包的 3.0+ 版本来设置 JSON 序列化程序选项。

参见: