【发布时间】:2020-02-08 09:42:31
【问题描述】:
而不是这个:
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 的实例,并为异常而不是规则覆盖。
如this q & a 所示,这是 Json.Net 的一个有用功能。我在the documentation 中查看了System.Text.Json 以及this GitHub repo 中的.NET Core。还有this one。
在 .NET Core 3 中似乎没有管理 JSON 序列化默认值的类比。还是我忽略了它?
-
更新 [2020-07-18]: 请参阅 this answer 了解 nuget package 以及支持默认设置的便捷方法。
-
更新 [2019 年 12 月 23 日]: 部分由于 community input 这个问题在 .NET 5.0 中是 added to the roadmap。
-
更新 [2019-10-10]: 如果有兴趣看到为
System.Text.Json.JsonSerializer实施此行为,请前往致Chris Yungmann指出的the open GitHub issue并称重。
【问题讨论】:
-
There doesn't seem to be an analog for managing JSON serialization defaults in Core-3-- 您是在谈论进出 API 的请求吗?还是对其他资源的请求和响应? -
@ps2goat 我不确定我是否理解您的问题。这里的问题是(反)序列化 JSON 字符串。它们可以来自任意数量的来源。
-
我之所以问,是因为在启动过程中有一些特殊的地方用于输入和输出格式化程序(例如,用于模型绑定)
-
啊,明白了。从这个意义上说,我认为我们的案例将属于“其他资源”。 @ps2goat
标签: c# json serialization .net-core system.text.json