Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting JsonConvert.DefaultSettings asp net core 2.0 not working as expected

I have following code inside Startup.cs and expecting it to override default serialization options. I want it to override every single serialization throughout my asp net core 2.0 project, but action return value that is not correct, I think this global property is not working in core 2.0

I have it written inside Configure exactly before app.UseMvc();

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.Objects,
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Converters = new List<JsonConverter> { new StringEnumConverter() }
            };
like image 535
Goga Koreli Avatar asked Sep 22 '17 08:09

Goga Koreli


People also ask

Should I use System Text JSON or Newtonsoft?

By default, Newtonsoft. Json does case insensitive property name matching during deserialization whereas System. Text. Json does case sensitive matching (with exception in ASP.Net core where you don't need to do anything to achieve behavior like Newtonsoft.

Is Newtonsoft JSON compatible with .NET core?

Json library is included in the runtime for . NET Core 3.1 and later versions. For other target frameworks, install the System.

Is Newtonsoft JSON still supported?

Yet Newtonsoft. Json was basically scrapped by Microsoft with the coming of . NET Core 3.0 in favor of its newer offering designed for better performance, System. Text.

Is JSON net the same as Newtonsoft JSON?

Json.net is made by newtonsoft.


1 Answers

In ASP.NET Core, this is configured when wiring up the services on the application in Startup.ConfigureServices. There is an fluent AddJsonOptions(Action<MvcJsonOptions>) extension to the IMvcBuilder returned by the AddMvc() extension. MvcJsonOptions exposes a SerializerSettings property which you can configure in your action code.

So instead of configuring once before registering MVC, it's done as part of the MVC registration.

Example incorporating your setup:

services.AddMvc()
  .AddJsonOptions( options =>
  {
    options.SerializerSettings.Formatting = Formatting.Indented;
    options.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    options.SerializerSettings.Converters.Add(new StringEnumConverter());
  });
like image 130
Marc L. Avatar answered Sep 25 '22 11:09

Marc L.