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
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.
Setting defaults for JsonContent in Asp.Net Core
As far as I know, there is no option for telling JsonContent.Create()
to use the global JsonSerializerOptions.
BUT you could use the options pattern to retrieve the global JsonSerializerOptions, you've added with AddJsonOptions(...);
.
Program.cs:
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
Options injected in Controller:
private readonly IOptions<JsonOptions> _JsonOptions;
public YourController(IOptions<JsonOptions> options)
{
_JsonOptions = options;
}
...
// in your request method:
using var request = new HttpRequestMessage(HttpMethod.Post, "myrequest");
using var content = new MultipartFormDataContent
{
{ new StreamContent(image), "data", "file.ext" },
{ JsonContent.Create(wfc, null, JsonOptions.Value.JsonSerializerOptions), "Object" }
};
request.Content = content;
using var res = await _httpClient.SendAsync(request);
...
To simplify things a bit more, you could use a static helper method, so you don't need to pass the type and you can just pass the options.
PascalCaseHelper.cs:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Net.Mime;
using System.Text;
using System.Text.Json;
namespace YourNamespace
{
public static class PascalCaseHelper
{
public static StringContent CreateJson(object data, IOptions<JsonOptions> options)
{
return new StringContent(
JsonSerializer.Serialize(data, options.Value.JsonSerializerOptions),
Encoding.UTF8,
MediaTypeNames.Application.Json);
}
}
}
// Usage:
{ PascalCaseHelper.CreateJson(myObject, _JsonOptions), "Object" }
Related Topics
Identityserver4 Role Based Authorization for Web API with ASP.NET Core Identity
Is There a Bigfloat Class in C#
How to Initialize a C# Dictionary with Values
Save and Retrieve Image (Binary) from SQL Server Using Entity Framework 6
What Is the Fastest Way I Can Compare Two Equal-Size Bitmaps to Determine Whether They Are Identical
Convert Base Class to Derived Class
Remove Text In-Between Delimiters in a String (Using a Regex)
Obtain Sha-256 String of a String
How to Call C# Dll Function from Vbscript
Sqlbulkcopy Insert with Identity Column
What Is the Static Variable Initialization Order Across Classes in C#
How to Return an Anonymous Type from a Method
Singleton by Jon Skeet Clarification
Differencebetween Linq to Xml Descendants and Elements
How to Monitor Clipboard Content Changes in C#