Instead of this:

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); 

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.

this q & a中所示,这是Json.Net的一个有用特性.我在the documentation中查找System.Text.Json,在this GitHub repo中查找.NET Core.和this one号.

在中,似乎没有类似的方法来管理JSON序列化默认值.网络核心3.还是我忽略了它?


  • UPDATE [2020-07-18]: See 100 for a 103 with convenience methods that honor default settings.

  • UPDATE [2019-12-23]: Due in part to vocal 100 this issue has been 101 for .NET 5.0.

  • 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不会expose default options.如果您使用的是特定的web框架,可能有一种方法可以通过该框架指定(反)序列化设置.否则,我建议创建自己的便利方法.

另请参见this open issue.

Json相关问答推荐

如何使用JQ有条件 Select 值

Bash和echo命令出现意外结果

如何在Vega中使标记的符号在鼠标指针悬停时可点击

使用json_query更新事实

将PostgreSQL转换为JSON对象

使用 jq 从带有转义反斜杠字符的嵌套 JSON 中提取数据

当并非所有子对象都有 Select 器字段时 Select

Moshi:序列化 List 时出现问题

Jolt 变换以展平 json 字符串数组

jq - 将父键值提取为子元素旁边的逗号分隔值

如何在linux中用jq过滤json数组?

PowerShell - JSON/PsCustomObject - 为什么我的数组被扁平化为一个对象?

Powershell JSON 操作

C# 合并 2 个几乎相同的 JSON 对象

将json字符反序列化为枚举

Json.NET 是否缓存类型的序列化信息?

Jersey 2.0 相当于 POJOMappingFeature

C++:使用 nlohmann json 从文件中读取 json 对象

case 类只有一个字段时如何将json转为 case 类

无法将 System.String 转换或转换为 Class 对象