2 years ago

#75576

test-img

jeff.eynon

Newtonsoft.Json Serializer settings not working on aspnet core app

I have the below configuration in my ASP.NET Core app

services
    .AddControllers(options =>
    {
        options.Filters.Add<CacheActionFilter>();
        options.Filters.Add<OutputModelActionFilter>();
    })
    .AddNewtonsoftJson(setupAction =>
    {
        setupAction.SerializerSettings.ContractResolver = new DefaultContractResolver
        {
            NamingStrategy = new SnakeCaseNamingStrategy()
        };
        // use the line below for CamelCase
        // setupAction.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        setupAction.SerializerSettings.Converters.Add(new StringEnumConverter());
        setupAction.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        setupAction.SerializerSettings.DateFormatString = "MM/dd/yyyy";
    });      

The only Serializer setting that is having any effect is the ReferenceLoopHandling setting. Other settings, like the StringEnumConverter seem to be ignored. The only way I can get enums to be converted to their string values is to add the JsonConverter attribute on my class property.

Am I missing something? Everything on the internet suggests this should work.

Currently I'm using net 3.1 but I also tried upgrading to net 6.0 and I get the same result.

EDIT FOR CLARITY The problem is with JSON being generated as output from my api methods. Not manually calling Json.Serialize.

c#

asp.net-core

.net-core

json.net

0 Answers

Your Answer

Accepted video resources