如何全局设置 System.Text.Json.JsonSerializer 的默认选项? [英] How to globally set default options for System.Text.Json.JsonSerializer?

查看:89
本文介绍了如何全局设置 System.Text.Json.JsonSerializer 的默认选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取而代之的是:

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 的实例,并覆盖异常而不是规则.

The hope is to not have to pass an instance of JsonSerializerOptions for our most common cases, and override for the exception, not the rule.

本问答中所示a,这是 Json.Net 的一个有用的特性.我查看了文档 用于 System.Text.Json 以及 此 GitHub 存储库 用于 .NET 核心.还有这个.

As indicated in this q & a, this is a useful feature of Json.Net. I looked in the documentation for System.Text.Json as well as this GitHub repo for .NET Core. And this one.

在 .NET Core 3 中似乎没有用于管理 JSON 序列化默认值的模拟.还是我忽略了它?

There doesn't seem to be an analog for managing JSON serialization defaults in .NET Core 3. Or am I overlooking it?

更新 [2019-12-23]: 部分原因是声音 社区意见 此问题已添加到 .NET 5.0 的路线图.

UPDATE [2019-12-23]: Due in part to vocal community input this issue has been added to the roadmap for .NET 5.0.

更新 [2019-10-10]: 如果有兴趣看到为 System.Text.Json.JsonSerializer 转到GitHub 公开问题Chris Yungmann 指出并权衡.

UPDATE [2019-10-10]: If interested in seeing this behavior implemented for System.Text.Json.JsonSerializer head on over to the open GitHub issue pointed out by Chris Yungmann and weigh in.

推荐答案

否,JsonSerializerOptions 不会公开 默认选项.如果您正在使用特定的 Web 框架,则可能有一种方法可以通过它指定(反)序列化设置.否则,我建议创建您自己的便捷方法.

No, JsonSerializerOptions does not expose the default options. If you are using a particular web framework there may be a way to specify (de-)serialization settings through that. Otherwise, I suggest creating your own convenience methods.

另见这个未决问题.

这篇关于如何全局设置 System.Text.Json.JsonSerializer 的默认选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆