json serializer settings for legacy asp.net core applications were set by adding AddMvc().AddJsonOptions(), but I don't use AddMvc() in asp.net core 3. So how can I set global json serialization settings?
- 73,173
- 13
- 183
- 186
- 2,244
- 4
- 17
- 23
-
If you don't use `AddMvc`, what _do_ you use? Are you using e.g. `AddControllers` or are you just not using MVC at all? – Kirk Larkin Oct 15 '19 at 10:09
-
@KirkLarkin i use default way of building asp.net core 3 app - `app.UseEndpoints(endpoints => { endpoints.MapControllers() })` and `services.AddControllers();` – Alex Zaitsev Oct 15 '19 at 10:10
-
Alright, so I guess you're using `AddControllers` in `ConfigureServices`, right? – Kirk Larkin Oct 15 '19 at 10:10
-
@KirkLarkin, yeah, right – Alex Zaitsev Oct 15 '19 at 10:11
6 Answers
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
- 2,045
- 14
- 19
- 73,173
- 13
- 183
- 186
-
6Adding "options.JsonSerializerOptions.IgnoreNullValues = true;" had no effect – zion Jan 17 '20 at 14:14
-
8To others who hit this page looking for Enum conversion: [JsonConverter(typeof(JsonStringEnumConverter))] public enum SomeEnum – Rafał Praniuk Apr 07 '20 at 15:09
-
For ASP.NET Core 3.1 (May/2021), we can specify the following to ask the JSON serializer not not serialize null values via the startup.cs file: services.AddControllers() .AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true); – Nalin Jayasuriya May 30 '21 at 10:47
Option A. AddControllers
This is still MVC, and requires Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget package, but you said you use AddControllers.
From Add Newtonsoft.Json-based JSON format support
services.AddControllers().AddNewtonsoftJson(options =>
{
// Use the default property (Pascal) casing
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
// Configure a custom converter
options.SerializerOptions.Converters.Add(new MyCustomJsonConverter());
});
Option B. DefaultSettings
JsonConvert.DefaultSettings = () => new JsonSerializerSettings (...)
JsonConvert.DefaultSettings Property
Gets or sets a function that creates default JsonSerializerSettings. Default settings are automatically used by serialization methods on JsonConvert, and ToObject () and FromObject(Object) on JToken. To serialize without using any default settings create a JsonSerializer with Create().
- 24,269
- 5
- 71
- 101
-
1Hi, this sets settings on Json.NET level, how can it be done on ASP.NET level? – Alex Zaitsev Oct 15 '19 at 10:06
-
2It configures the settings on ASP.NET level, meaning default ModelBinding now happens using NewtonsoftJson serializer. – MrClan Mar 11 '20 at 05:55
-
Thank you, Option A worked for me. Upgraded from 2.2 to 3.1 and my endpoint broke because `System.Text.Json` doesn't handle polymorphism or enums properly. Nice easy way to change the default serializer. – static_void Apr 14 '20 at 14:11
-
1Example for ignroing null values and converting enums to strings: `services.AddControllersWithViews().AddNewtonsoftJson(o => { o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; o.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); });` – jnt Sep 18 '20 at 12:50
-
Not sure I'd do this on a new project, but moving legacy code to a new version... +1 for the `AddNewtonsoftJson()` and the link to the docs. – ThatBlairGuy Jul 16 '21 at 18:05
Adding Newtonsoft is not necessary, quite a problems with adding Newtonsoft compatibility packages on .Net Core 3.0 project.
See also https://github.com/aspnet/AspNetCore/issues/13564
Of course, one would celebrate property naming PascalCase, NA at the moment...
So null for PropertyNamingPolicy means PascalCase, which is obviously not very good.
// Pascal casing
services.AddControllersWithViews().
AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
- 1,380
- 1
- 13
- 15
-
2Thank you @OSP, but what do you exactly mean "obviously not very good"? – Arash Ghasemi Rad Jan 31 '21 at 06:17
You can try System.Text.Json, the newly released Json nuget package converter. Newtonsoft no longer works very well in .Net Core.
Startup.cs as below
You can write this code inside the configirationSetting method.
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.Converters.Add (new JsonStringEnumConverter ());
});
- 42,843
- 5
- 48
- 70
- 129
- 1
- 7
-
41. Not so newly 2.Can you please explain claim _"Newtonsoft no longer works very well in .Net Core"_? 3. what is _"configirationSetting method"_ ? – Guru Stron Dec 14 '20 at 00:17
-
1Hello @GuruStron, 1) it is newly, beacuse it is **net core 3.1** libary supported. (https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/) 2) (https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to?pivots=dotnet-5-0 ) 3) Microsoft is now using new nuget packages from its own freamwork in all software. For this reason, it withdraws support from many of them and directs them to their own packages. **Newtonsoft.Json** provides support, but now **Microsoft** wants its own package for Core. – Onur Dikmen Dec 24 '20 at 06:29
-
11) Article you've linked in this point is around 1.5 years old 2) this one is about HOW to migrate and does not explain claim in question =)) 3) this point does not answer question _"what is "configirationSetting method""_ =) – Guru Stron Dec 25 '20 at 16:17
In .net6 add this code after .AddControllers() in program.cs file:
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
- 4,146
- 2
- 14
- 23
1.install NuGet : Microsoft.AspNetCore.Mvc.NewtonsoftJson or
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.2" />
</ItemGroup>
2. Add Startup.cs :
public void ConfigureServices(IServiceCollection services)
{
//JSON Serializer
services.AddControllers().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
}
- 639
- 7
- 11