c# - .NET 6 - 带有 CamelCase 的 AddJsonOptions 不起作用

标签 c# .net .net-6.0 system.text.json jsonserializer

我已经尝试在 .NET 6 上使用 camelCase insentive 来反序列化来自 API 的内容

我在 Startup.cs 中这样配置,但它不起作用

            .AddControllers()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.IgnoreNullValues = true;
            });

我用这个分辨率来解决:https://github.com/andre-ss6 https://github.com/dotnet/runtime/issues/31094#issuecomment-543342051

他推荐使用下面的代码:

            ((JsonSerializerOptions)typeof(JsonSerializerOptions)
    .GetField("s_defaultOptions",
        System.Reflection.BindingFlags.Static |
        System.Reflection.BindingFlags.NonPublic).GetValue(null))
    .PropertyNameCaseInsensitive = true;

我试过了,但我觉得很复杂,因为它使用了反射,我不知道该怎么想,有人有其他解决方案或解释吗?

我这样反序列化它:

        var content = await response.Content.ReadAsStringAsync(cancellationToken);

        var result = JsonSerializer.Deserialize<InvestimentFundsResponseData>(content);

我的类是,你怎么看到的,我不用属性[JsonPropertyName]

    public class InvestimentFundsResponseData
    {
      public IEnumerable<InvestmentFundsResponse> Data { get; set;}
    }

    public class InvestmentFundsResponse
    {
      public Guid Id { get; set; }
    }

最佳答案

JsonSerializer.Deserialize 不使用由 AddJsonOptions 配置的 JsonSerializerOptions,手动创建和传递所需的选项(可能从 DI 解析)通过 JsonOptions):

var result = JsonSerializer.Deserialize<InvestimentFundsResponseData>(content, new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    Converters = {new JsonStringEnumConverter()},
    IgnoreNullValues = true
});

关于c# - .NET 6 - 带有 CamelCase 的 AddJsonOptions 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72034017/

相关文章:

.net - 用自定义异步计时器类替换 Threading.Timer?

.net - .Net 如何获得 UTC?

c# - .NET 6 中的 using 语句/指令在哪里

c# - Convert.FromBase64String 给出错误 "The input is not a valid Base-64 string"

c# - 如何将图表的轴绑定(bind)到 List() 的特定索引?

c# - 在移动到上一条或下一条记录之前,数据绑定(bind)不更新数据库

c# - 正则表达式获取指定单词后的第一个单词

c# - 从字典中获取除 "foreach"之外的键和值

wpf - 在带有 .NET 6 运行时的 Windows 10 上启动 WPF 应用程序不起作用

c# - 一个接收 PictureBox 和 String 的方法,两者都在里面定义,但最后 String 将为空