gpt4 book ai didi

c# - 访问 Json 序列化器选项以避免在 Azure Functions v3 中序列化 null

转载 作者:行者123 更新时间:2023-12-03 01:22:54 24 4
gpt4 key购买 nike

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

这是 v3 函数

我已经尝试过

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

在我的函数的启动中

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

如何强制使用 Newtonsoft?

干杯

保罗

最佳答案

2023 年编辑

各种函数(和 MVC)版本有不同的设置方法,并且可能使用 Newtonsoft.Json 或 System.Text.Json

链接:

https://github.com/Azure/azure-functions-host/issues/5841#issuecomment-987168758

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

测试

原始答案(旧版本)

改编自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 类添加到您的 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.

关于c# - 访问 Json 序列化器选项以避免在 Azure Functions v3 中序列化 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68420349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com