117

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?

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Alex Zaitsev
  • 2,544
  • 5
  • 18
  • 27

6 Answers6

104

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

Bart
  • 2,062
  • 15
  • 19
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
  • 6
    Adding "options.JsonSerializerOptions.IgnoreNullValues = true;" had no effect – zion Jan 17 '20 at 14:14
  • 9
    To 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
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().

tymtam
  • 31,798
  • 8
  • 86
  • 126
  • 1
    Hi, this sets settings on Json.NET level, how can it be done on ASP.NET level? – Alex Zaitsev Oct 15 '19 at 10:06
  • 2
    It 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
  • 2
    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()); });` – 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
46

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;
        });
OSP
  • 1,458
  • 1
  • 14
  • 15
10

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 ());
      });  
Onur Dikmen
  • 339
  • 1
  • 6
  • 17
  • 4
    1. 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
  • 1
    Hello @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://learn.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
  • 1
    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""_ =) – Guru Stron Dec 25 '20 at 16:17
  • 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. – Douglas Gaskell Dec 11 '22 at 00:28
  • 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. – Onur Dikmen Dec 12 '22 at 12:54
5

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

builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
M Komaei
  • 7,006
  • 2
  • 28
  • 34
2

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;
           });
    }
Fahimeh Ahmadi
  • 813
  • 8
  • 13