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)?
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());
Simply use this (Should work in .NET 5 also)
services.AddMvc().AddJsonOptions(o =>
{
o.JsonSerializerOptions.PropertyNamingPolicy = null;
o.JsonSerializerOptions.DictionaryKeyPolicy = null;
});
This should work.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly