.NET 8 中的 JsonSerializerOptions 全局设置

问题描述 投票:0回答:1

在 .NET 8 之前,在 Azure 函数中设置全局设置通常可以正常工作。现在,相同的代码在 .NET 8 和 Azure Functions v4 中不起作用:

        // Setting global System.Text.Json.JsonSerializerOptions
        services.Configure<JsonSerializerOptions>(options =>
        {
            options.PropertyNameCaseInsensitive = true;
            options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;  // Property is ignored if its value is null. This is applied only to reference-type properties and fields.
        });

不再支持此功能吗?我找不到任何有关如何在 .NET 8 中执行此操作的文档。

azure-functions .net-8.0 system.text.json
1个回答
0
投票

在 .NET 8 中,我需要将其注入到我的 Azure Functions 构造函数中才能工作。下面是将 JSON 序列化选项注入到我的主构造函数中的示例:

public class Function1(ILogger<Function1> logger, IOptions<JsonOptions> jsonOptions)
{
   private readonly ILogger<Function1> _logger = logger;
   private readonly JsonSerializerOptions _jsonOptions = jsonOptions.Value.SerializerOptions;
   ...
}

然后在反序列化方法中使用它作为参数:

var messageData = JsonSerializer.Deserialize<MyDTO>(message.Body, _jsonOptions);

这应用了我的设置,忽略 JSON 中字段名称的大小写。

© www.soinside.com 2019 - 2024. All rights reserved.