【问题标题】:Access Json Serializer options to avoid serializing null in Azure Functions v3访问 Json 序列化程序选项以避免在 Azure Functions v3 中序列化 null
【发布时间】:2021-07-17 12:04:28
【问题描述】:

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

这是一个 v3 函数

我试过了

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

在我的功能启动中

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

如何强制使用 Newtonsoft?

干杯

保罗

【问题讨论】:

标签: c# json azure json.net azure-functions


【解决方案1】:

改编自Add JSON Options In HTTP Triggered Azure Functions

先决条件

您需要确保满足here 中提到的所有先决条件

从该文档页面:

在使用依赖注入之前,必须安装以下 NuGet 包:

  • Microsoft.Azure.Functions.Extensions
  • Microsoft.NET.Sdk.Functions 包版本 1.0.28 或更高版本
  • Microsoft.Extensions.DependencyInjection(目前仅支持 3.x 及更早版本)

注意:

本文中的指导仅适用于 C# 类库函数,它们与运行时一起在进程内运行。此自定义依赖注入模型不适用于 .NET 隔离函数,它允许您在进程外运行 .NET 5.0 函数。 .NET 隔离进程模型依赖于常规的 ASP.NET Core 依赖注入模式。

代码

将启动类添加到您的 Azure 函数项目,如下所示:

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;
            });
        }
    }
}


这会将 JSON 选项设置为忽略空值。

【讨论】:

  • 这在构建于 ASP.Net core 3.0+ 之上的 Functions V3 中不起作用
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2019-08-19
    相关资源
    最近更新 更多