Skip to content

Instantly share code, notes, and snippets.

@nbellocam
Created March 14, 2016 13:14
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbellocam/147a7d47c7a90490798e to your computer and use it in GitHub Desktop.
Save nbellocam/147a7d47c7a90490798e to your computer and use it in GitHub Desktop.
Asp.net core: Configure MVC to use camelCase for json serializer
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
@ranouf
Copy link

ranouf commented Nov 27, 2019

Hi,

SerializerSettings is not available anymore with .net core 3.0, it has been replaced by JsonSerializerOptions which doesnt have ContractResolver , do you know by what do I need to replace it?

@nbellocam
Copy link
Author

Hi @ranouf,

Honestly, I'm not sure as I didn't use it yet, but maybe this can help you: https://stackoverflow.com/a/58392418.

Thanks,

@ranouf
Copy link

ranouf commented Nov 28, 2019

Thanks for your fast answer :)

The solution is to use "AddNewtonsoftJson" instead of "AddJsonOptions", like this no need to change the rest of your code

@stonestecnologia
Copy link

stonestecnologia commented Apr 28, 2020

Hi !

      services.AddControllers(config =>
      {
        AuthorizationPolicy p = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
        config.Filters.Add(new AuthorizeFilter(p));
      }).AddNewtonsoftJson(options =>
        {
          options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
          options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
          options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
        }
      );

@yingDev
Copy link

yingDev commented Jul 24, 2020

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews().AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
    }

@ngnam
Copy link

ngnam commented Aug 2, 2021

Default in .netcore5 hadd is casePascal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment