How to set json serializer settings in asp.net core 3?
Asked Answered
M

6

123

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?

Mayhem answered 15/10, 2019 at 10:0 Comment(4)
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?Committeewoman
@KirkLarkin i use default way of building asp.net core 3 app - app.UseEndpoints(endpoints => { endpoints.MapControllers() }) and services.AddControllers();Mayhem
Alright, so I guess you're using AddControllers in ConfigureServices, right?Committeewoman
@KirkLarkin, yeah, rightMayhem
C
111

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

Committeewoman answered 15/10, 2019 at 10:21 Comment(3)
Adding "options.JsonSerializerOptions.IgnoreNullValues = true;" had no effectLimiter
To others who hit this page looking for Enum conversion: [JsonConverter(typeof(JsonStringEnumConverter))] public enum SomeEnumShortcake
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);Yajairayajurveda
K
76

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

Kokand answered 15/10, 2019 at 10:3 Comment(5)
Hi, this sets settings on Json.NET level, how can it be done on ASP.NET level?Mayhem
It configures the settings on ASP.NET level, meaning default ModelBinding now happens using NewtonsoftJson serializer.Durst
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.Lobotomy
Example 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()); });Wrenn
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.Nougat
P
47

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;
        });
Paxton answered 8/12, 2019 at 16:5 Comment(1)
Thank you @OSP, but what do you exactly mean "obviously not very good"?Cynde
P
12

You can try System.Text.Json, the newly released Json nuget package converter. 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 ());
      });  
Potent answered 14/12, 2020 at 0:9 Comment(6)
1. Not so newly 2.Can you please explain claim "Newtonsoft no longer works very well in .Net Core"? 3. what is "configirationSetting method" ?Henriques
Hello @GuruStron, 1) it is newly, beacuse it is net core 3.1 libary supported. (devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis) 2) (learn.microsoft.com/en-us/dotnet/standard/serialization/… ) 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.Potent
1) 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"" =)Henriques
Even in 2022 System.Text.Json is missing core flexibility features that make is a far from ideal candidate for JSON serialization. JSON is designed to be greedy in operation, System.Text.Json continually fails to match that requirement.Hotfoot
Software is an ever-evolving and greedy thing. The compenent that has met the needs for a few years now does not. That's why the software is constantly evolving. Lots of new programming languages ​​are coming out, requirements are changing.I said Microsoft's suggestion and now Microsoft offers its own add-ons and does not recommend 3-part add-ons. Currently net core works very stable with Microsoft's plugins.Potent
I also added "options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;" for similar behavior to .NET framework.Kalmar
J
5

In .net6 add this code after .AddControllers() in program.cs file:

builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
Jehad answered 26/1, 2022 at 14:30 Comment(3)
Question is about net 3.1Penicillin
My app has the old WebHost.CreateDefaultBuilder(args) left, which does not have .Services. How do I set the JsonOptions there?Inspirational
Add it after AddControllers() methos in Startup.cs file.Jehad
O
3

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;
           });
    }
Orleanist answered 1/10, 2021 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.