Json.net global settings
So, this was added to Json.net 5.0 Release 5
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
From the release notes:
Set once with
JsonConvert.DefaultSettings
in an application, the default settings will automatically be used by all calls toJsonConvert.SerializeObject
/DeserializeObject
, andJToken.ToObject
/FromObject
. Any user supplied settings to these calls will override the default settings.Because there are cases where JSON should not be customized, e.g. a Facebook or Twitter library, by default
JsonSerializer
won’t useDefaultSettings
, providing an opt-out for those frameworks or for places in your application that shouldn’t use default settings. To create aJsonSerializer
that does use them there is a newJsonSerializer.CreateDefault()
method.
Do note that when ASP.NET invokes Newtonsoft directly, e.g. in model binding or response formatting, it opts out of using these global default settings. To configure defaults used internally by ASP.NET see this answer by Andrei.
Set default global json serializer settings
Setting the JsonConvert.DefaultSettings
did the trick.
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Objects,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
How to globally set default options for System.Text.Json.JsonSerializer?
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.
How to set json serializer settings in asp.net core 3?
AddMvc
returns an IMvcBuilder
implementation, which has a corresponding AddJsonOptions
extension method. The new-style methods AddControllers
, AddControllersWithViews
, and AddRazorPages
also return an IMvcBuilder
implementation. Chain with these in the same way you would chain with AddMvc
:
services.AddControllers()
.AddJsonOptions(options =>
{
// ...
});
Note that options
here is no longer for Json.NET, but for the newer System.Text.Json
APIs. If you still want to use Json.NET, see tymtam's answer
How to tell Json.Net globally to apply the StringEnumConverter to all enums
Add a StringEnumConverter
to the JsonSerializerSettings
Converters collection.
Documentation: Serialize with JsonConverters
If you want the serializer to use camelCasing, you can set this as well:
SerializerSettings.Converters.Add(
new StringEnumConverter { CamelCaseText = true });
This will serialize SomeValue
to someValue
.
Json.NET serializes enum as string even with default settings
This is happening because JsonConvert.SerializeObject
applies the incoming settings on top of the default settings, by internally calling JsonSerializer.CreateDefault(JsonSerializerSettings settings)
. I don't know if/where this behavior is documented, but it's visible in the source code. Thus the default list of converters will be used in addition to the empty list of locally specified converters, meaning the default StringEnumConverter
will get used.
You have a couple options to work around this:
Construct the
JsonSerializer
yourself without using the default settings:public static class JsonExtensions
{
public static string SerializeObjectNoDefaultSettings(object value, Formatting formatting, JsonSerializerSettings settings)
{
var jsonSerializer = JsonSerializer.Create(settings);
jsonSerializer.Formatting = formatting;
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = jsonSerializer.Formatting;
jsonSerializer.Serialize(jsonWriter, value);
}
return sw.ToString();
}
}And then use it like:
var json = JsonExtensions.SerializeObjectNoDefaultSettings(value, Formatting.None, new JsonSerializerSettings());
Supersede the default
StringEnumConverter
with one that does not serialize enums as strings, for instance:public class IntegerEnumConverter : StringEnumConverter
{
public override bool CanRead { get { return false; } }
public override bool CanWrite { get { return false; } }
}And then use it like:
var json = JsonConvert.SerializeObject(value, Formatting.None, new JsonSerializerSettings { Converters = new JsonConverter[] { new IntegerEnumConverter() } });
The locally specified converter will be picked up in preference to the default converter.
Temporarily nulling out the JsonConvert.DefaultSettings
would be a bad idea since it would not be thread-safe.
Related Topics
Should You Obfuscate a Commercial .Net Application
How to Run Multiple SQL Commands in a Single SQL Connection
Get All Registered Routes in ASP.NET Core
Memorystream.Close() or Memorystream.Dispose()
How to Effectively Draw on Desktop in C#
C# Sortable Collection Which Allows Duplicate Keys
Fake-Scrolling Containers with Very Many Controls
Replace Unicode Escape Sequences in a String
How to Convert Securestring to System.String
Wpf C#: Rearrange Items in Listbox via Drag and Drop
C# - Volatile Keyword Usage VS Lock
.Net, Event Every Minute (On the Minute). Is a Timer the Best Option
ASP.NET MVC Dropdown List from Selectlist
Double.Tryparse or Convert.Todouble - Which Is Faster and Safer