How to globally set default options for System.Text.Json.JsonSerializer?

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?

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.

JsonSerializerOptions Class (System.Text.Json), System.Text.Json.dll. Provides options to be used with JsonSerializer. Gets or sets the default buffer size, in bytes, to use when creating temporary buffers. Enable Global Serialization settings. The above-discussed techniques apply the JSON serialization settings globally for all the controller in the ASP.NET Core API or MVC based application. Using services.AddMvc or service.AddController along with AddJsonOptions helps us enabling global settings for all controllers in a service.

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.

public static class DeserializeExtensions
{
    private static JsonSerializerOptions defaultSerializerSettings = new JsonSerializerOptions();

    // set this up how you need to!
    private static JsonSerializerOptions featureXSerializerSettings = new JsonSerializerOptions();


    public static T Deserialize<T>(this string json)
    {       
        return JsonSerializer.Deserialize<T>(json, defaultSerializerSettings);
    }

    public static T DeserializeCustom<T>(this string json, JsonSerializerOptions settings)
    {
        return JsonSerializer.Deserialize<T>(json, settings);
    }

    public static T DeserializeFeatureX<T>(this string json)
    {
        return JsonSerializer.Deserialize<T>(json, featureXSerializerSettings);
    }
}

Then you call it as a method on a string, whether literal or a variable.

    Car result = @"{""Wheels"": 4, ""Doors"": 2}".DeserializeFeatureX<Car>();

Migrate from Newtonsoft.Json to System.Text.Json, System.Text.Json option to ignore default values during serialization #779 Thrown if this property is set after serialization or deserialization has occurred. granularity: should the option be global (on JsonSerializerOptions), per-property [JsonSerializer] Provide option to specify a custom default value for a type, property  Currently the "default" option is on a private static variable. This means it can only contain default settings. Also, FWIW, we also discussed add assembly-level attributes that can configure things like the naming policy. This would support some of the scenarios without having to specify where the default option lives.

System.Text.Json option to ignore default values during serialization , It should be a given that .net let us set default settings for the serializer, the capability to enable setting the json serializer options globally, once. The default behavior of System.Text.Json.JsonSerializer is to match the  Priority scenarios (for .NET 5) Ignoring default values See #779 for more info. We currently have global and per-property options to ignore null when serializing and deserializing reference types.

A workaround has been proposed by GitHub user andre-ss6 as follows:

((JsonSerializerOptions)typeof(JsonSerializerOptions)
    .GetField("s_defaultOptions", 
        System.Reflection.BindingFlags.Static |
        System.Reflection.BindingFlags.NonPublic).GetValue(null))
    .PropertyNameCaseInsensitive = true;

Api proposal: Change JsonSerializer default settings · Issue #31094 , area-System.Text.Json · Jsonserializer and record types with "primary" constructor Model { [JsonConverter(typeof(ValueConverter)] public string Value {get;set;} } options to ignore CLR default values during serialization (API approved). create the converter in a IConfigureOptions<JsonOptions> and globally add it to  This property was set after serialization or deserialization has occurred. Remarks For more information, see Exclude all null value properties and Ignore null when deserializing .

(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.

JsonConvert.DefaultSettings = () => MySuperJsonSerializerSettings;

and then

var json = JsonConvert.SerializeObject(o1);
var o2 = JsonConvert.DeserializeObject(x);

area-System.Text.Json, NET Core 3.0 the default JSON serializer has been changed from Newtonsoft.​Json to System.Text.Json. For projects and libraries switching to the new typeToConvert, JsonSerializerOptions options) { var name = reader. Theme Style settings are global settings that allow you to set default styling options for various elements, such as Backgrounds, Headings, Buttons, Images, and Form Fields. These settings override the theme styling settings and takes its place, allowing you to use Elementor to set styles for elements not built by Elementor.

ASP.NET Core 3.0, It also provides types to read and write JSON text encoded as UTF-8, and to create NET Core JSON Serializer belonging to the System.Text.Json namespace by default. A default serializer is a new feature for RestClient. be improved by changing the serialization option PropertyNameCaseInsensitive to  The default serializer in ASP.NET Web API (at least in Beta) is the DataContractJsonSerializer with all of its warts and inability to not serializer non-typed objects. In this post I'll talk about the issues and how to plug-in alternate JSON parsers to handle more complete JSON serialization in Web API.

System.Text.Json Rest Client – ChristianFindlay.com, NET Core 3.0 the default JSON serialiser has been changed from Newtonsoft.​Json to the native System.Text. You might be thinking “How can I globally set the default options for the JsonSerializer?“ It would be nice if we  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.

Serialisely painful, When you do this, it's basically telling the global settings to get public class SerializedModel { [JsonProperty("MyFirstProperty")] public int MyFirstProperty { get; set; } property without the JsonProperty attribute is using the default . NET (newtonsoft) but by default is using System.Text.Json. Did You have  System.Text.Json.JsonSerializer is built on top of Utf8JsonReader and Utf8JsonWriter to provide a fast, low-memory serialization option when working with JSON documents and fragments. Here is an example of serializing an object to JSON:

Comments
  • There doesn't seem to be an analog for managing JSON serialization defaults in Core-3 -- are you talking about requests into and out of your API? or requests and responses to other resources?
  • @ps2goat I am not sure I understand your question. The matter here is (de)serializing JSON strings. They could come from any number of sources.
  • I was asking because there are special places during startup for input and output formatters (e.g., for model binding)
  • Ah, gotcha. In that sense I think our case would fall under "other resources." @ps2goat