UPDATE [2019-12-23]: Due in part to vocal community input this issue has been added to the roadmap 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.
Instead of this:
JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
// etc.
};
JsonSerializer.Deserialize<SomeObject>(someJsonString, options);
I would like to do something like this:
// 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);
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.
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.
There doesn't seem to be an analog for managing JSON serialization defaults in .NET Core 3. Or am I overlooking it?
A workaround has been proposed by GitHub user andre-ss6 as follows:
(If you ever switch to using Json.NET)
I prefer and recommend being explicit and pass settings to all calls, but you can set defaults with DefaultSettings.
and then
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.See also this open issue.
You can create an extension method. Here's an example
I use separate methods vs having to build special settings, so that all the settings will be in a single spot and easily reusable.
Then you call it as a method on a string, whether literal or a variable.
The default options are not exposed in
JsonSerializer
for .NET Core 3.1. However, as of December, 2019 this has been added to the road map for 5.0.The release of .NET 5.0 is expected November, 2020. But there's no guarantee this particular issue will be addressed at any particular time. Other than waiting, these answers suggest workarounds: