Skip to content

Instantly share code, notes, and snippets.

@scheffler
Last active August 26, 2020 13:17
Show Gist options
  • Save scheffler/828b4d913963a1da9588d9035afda240 to your computer and use it in GitHub Desktop.
Save scheffler/828b4d913963a1da9588d9035afda240 to your computer and use it in GitHub Desktop.
Preserve JSON case using NewtonSoft in aspnet core 3.x

With aspnet core 3.x, the default Text JSON serializer as well as the Newtonsoft extension (if you're still holding on to Newtonsoft like I am) apply a camel casing naming strategy.

This means that for your upper case properties in C# land, they get translated to lower case starting letters in javascript. This is great. Unless you're dealing with a legacy codebase where the javascript is expecting the starting upper cases.

The fix is easy. Just set contract resolver in your Startup to an instance of DefaultContractResolver.

using json.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace json
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var resolver =
services.AddControllersWithViews()
.AddNewtonsoftJson(opts =>
{
opts.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
@taylor-brian
Copy link

Can you just do:
opts.SerializerSettings.ContractResolver = new DefaultContractResolver()

Looks like their DefaultNamingStrategy still behaves like your PreserveCaseNamingStrategy, where it just returns the name of the property.

@scheffler
Copy link
Author

Oh, nice catch. Yes, that does work

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