gpt4 book ai didi

c# - 如何全局设置 System.Text.Json.JsonSerializer 的默认选项?

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

取而代之的是:

JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
// etc.
};
var so = JsonSerializer.Deserialize<SomeObject>(someJsonString, options);
我想做这样的事情:
// This property is a pleasant fiction
JsonSerializer.DefaultSettings = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
// etc.
};

// This uses my options
var soA = JsonSerializer.Deserialize<SomeObject>(someJsonString);

// And somewhere else in the same codebase...
// This also uses my options
var soB = JsonSerializer.Deserialize<SomeOtherObject>(someOtherJsonString);

希望不必传递 JsonSerializerOptions 的实例对于我们最常见的情况,并覆盖异常(exception),而不是规则。
this q & a 所示,这是 Json.Net 的一个有用功能。我看了 the documentationSystem.Text.Json以及 this GitHub repo对于 .NET 核心。和 this one .
.NET Core 3 中似乎没有用于管理 JSON 序列化默认值的模拟。还是我忽略了它?
  • 更新 [2020-07-18]:this answer对于 nuget package 使用尊重默认设置的便捷方法。
  • 更新 [2019-12-23]:部分原因是声乐 community input此问题已added to the roadmap对于 .NET 5.0。
  • 更新 [2019-10-10]:如果有兴趣看到为 实现的此行为System.Text.Json.JsonSerializer 前往 the open GitHub issue Chris Yungmann 指出并称重。
  • 最佳答案

    不,JsonSerializerOptions不暴露 default options .如果您正在使用特定的 Web 框架,则可能有一种方法可以通过它指定(反)序列化设置。否则,我建议创建您自己的便捷方法。

    另见 this open issue .

    关于c# - 如何全局设置 System.Text.Json.JsonSerializer 的默认选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58331479/

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