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.