How can I set JSON Serializer in ASP.NET Core (.NET 5)?


Hello, I am trying to work on JSON in ASP.NET Core MVC (using .NET 5.0 version), but I am not able to set JSON Serializer settings using it, I tried to use below code

 services.AddJsonOptions();

In startup.cs, but it is not working, how can I make it work ASP.NET Core (.NET 5)?


Asked by:- bhanu
0
: 342 At:- 8/31/2021 3:55:14 PM
ASP.NET Core C# JSON serializer






1 Answers
profileImage Answered by:- vikas_jk

You can using JSON serializer in ASP.NET Core (Using .NET 5), by adding Nuget package first

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson

and then in your Startup.cs, use the below code

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddControllers().AddNewtonsoftJson(options =>
            {
                // Use the default property (Pascal) casing
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });
        }

or, if you want to add Custom Serializer, you can add this code, in above configuration

   // Configure a custom converter
    options.SerializerOptions.Converters.Add(new YourCustomJsonConverter());

Using .NET Core 3

Simply use this (Should work in .NET 5 also)

services.AddMvc().AddJsonOptions(o =>
{
    o.JsonSerializerOptions.PropertyNamingPolicy = null;
    o.JsonSerializerOptions.DictionaryKeyPolicy = null;
});

This should work.

1
At:- 8/31/2021 4:10:06 PM
thanks for quick answer, was helpful. 0
By : bhanu - at :- 8/31/2021 4:34:55 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use