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

标签 c# json serialization .net-core system.text.json

取而代之的是:

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/

    相关文章:

    c# - 将 C# 对象转换为 Json 对象

    c# - 返回所有包含特定值的列名

    c# - 如何使用户能够从 ASP.NET MVC 发送电子邮件?

    c# - 即使预期没有异常也使用 try catch

    json - 记录 JSON 正文可以,但不能记录 body.item。给出未定义的

    javascript - 返回值显示为字符串而不是 json

    c# - 如何在 azure 函数中禁用 XML 序列化

    c# - 来自多个模板的 ITextSharp 多页 PDF

    json - 高效灵活的 Javascript 库来查询允许聚合的大型 JSON 文件?

    java - @ResponseBody 使用 ArrayLists 序列化错误