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

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

问题描述

更新: 如果有兴趣看到为 System.Text.Json.JsonSerializer 实施的此行为,请转到 公开的GitHub问题

UPDATE: 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 options = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    // etc.
};
JsonSerializer.Deserialize<SomeObject>(someJsonString, options);

我想做这样的事情:

// This property is a pleasant fiction
JsonSerializer.DefaultSettings = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    // etc.
};

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

// And somewhere else in the same codebase...
// This also uses my options
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.

此q&一个,这是Json.Net的有用功能.我查看了文档(用于System.Text.Json)以及此GitHub存储库(用于Core).而这一个.

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 Core. And this one.

在Core-3中似乎没有类似的方法可以管理JSON序列化默认设置.还是我忽略了它?

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

推荐答案

否,JsonSerializerOptions不公开

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天全站免登陆