How to turn off or handle camelCasing in JSON response ASP.NET Core?

C#.NetAngularjsJsonasp.net Core

C# Problem Overview


I'm running through a WintellectNOW course on ASP.NET Core/Web API/Angular 2. I have the API portion implemented, but for whatever reason, the JSON that is being returned has the variable names being lowercased.

The returned JSON is formatted like...

[ {"id":1,"name":"Bowler","color":"black","count":1}, {"id":2,"name":"Fedora","color":"red","count":1}, {"id":3,"name":"Baseball Cap","color":"blue","count":3}]

I'm expecting...

[ {"Id":1,"Name":"Bowler","Color":"black","Count":1}, {"Id":2,"Name":"Fedora","Color":"red","Count":1}, {"Id":3,"Name":"Baseball Cap","Color":"blue","Count":3}]

Based on the C# model of...

namespace HatCollection.Models
{
    public class Hat
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Color { get; set; }
        public int Count { get; set; }
    }
}

I even went as far as decorating the properties with [DataMember(Name = "Id")] just to make sure and it still didn't matter.

On the off chance, it's relevant the Action and instance variable in the controller...

private static readonly List<Hat> MyHats = new List<Hat>
{
    new Hat {Id = 1, Name = "Bowler", Color = "black", Count = 1 },
    new Hat {Id = 2, Name = "Fedora", Color = "red", Count = 1 },
    new Hat {Id = 3, Name = "Baseball Cap", Color = "blue", Count = 3 }
};

[HttpGet]
public IEnumerable<Hat> Get()
{
    return MyHats;
}

How do I turn off the camelCase functionality, so that ASP.NET Core returns the property names without changing them?

C# Solutions


Solution 1 - C#

In Asp.Net Core 3.0 some things have changed. For camelCase do nothing that is out of the box. For PascalCase or another set style use.

services.AddMvc(setupAction=> {
            setupAction.EnableEndpointRouting = false;
        }).AddJsonOptions(jsonOptions =>
        {
            jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

In Startup.cs ConfigureServices section

Solution 2 - C#

For those who needs a solution about a PascalCase within Api Project that has not the Mvc services you should add this after AddControllers services

 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddJsonOptions(jsonOptions =>
                {
                    jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
                } ;
        }

Solution 3 - C#

For Asp.Net Core 3.1 using the NewtonSoft.Json

services.AddControllers()
		.AddNewtonsoftJson(options =>
		{
			options.UseMemberCasing();
		});

Solution 4 - C#

In ASP.NET Core <3.0, JSON properties are camelCased by default (per this announcement).

You can disable this by replacing

services.AddMvc();

with

services
    .AddMvc()
    .AddJsonOptions(opt => opt.SerializerSettings.ContractResolver
        = new DefaultContractResolver());

in your Startup.cs file. You'll have to add using Newtonsoft.Json.Serialization; to the top of the file.

With the DefaultContractResolver in place, the property names will be represented verbatim in the JSON output. No need for DataMember attributes.

Solution 5 - C#

Here is the answer for .net 5 :

https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0

> Configure System.Text.Json based formatters Features for the > System.Text.Json based formatters can be configured using > Microsoft.AspNetCore.Mvc.JsonOptions.JsonSerializerOptions. > > The > default formatting is camelCase. The following highlighted code sets > PascalCase formatting: > > C#

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

Solution 6 - C#

Another solution in Asp.Net.Core 2.2 as following:

services.AddMvc()
.AddJsonOptions(jsonOptions => jsonOptions.UseMemberCasing())
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Solution 7 - C#

You have to change the DefaultContractResolver which uses camelCase by default. Just set the NamingStatergy as null.

This should be done in the StartUp.ConfirgureService as follows.

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .AddMvcOptions(o => o.OutputFormatters.Add(
                new XmlDataContractSerializerOutputFormatter()));

            .AddJsonOptions(o => {
                if (o.SerializerSettings.ContractResolver != null)
                {
                    var castedResolver = o.SerializerSettings.ContractResolver
                        as DefaultContractResolver;
                    castedResolver.NamingStrategy = null;
                }
            });
    }

Option 2

Use JSonProperty as follows.

public class Hat
{
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("color")]
    public string Color { get; set; }
    [JsonProperty("count")]
    public int Count { get; set; }
}

Solution 8 - C#

I am using the following solution because

  • a) I prefer using the .Net Core built in System.Text.Json serializer and
  • b) I do not want to rely on the not documented internal behaviour of jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;.

.

services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = new MyTransparentJsonNamingPolicy();
    });

where:

public class MyTransparentJsonNamingPolicy : JsonNamingPolicy
{
    // You can came up any custom transformation here, so instead just transparently
    // pass through the original C# class property name, it is possible to explicit
    // convert to PascalCase, etc:
    public override string ConvertName(string name)
    {
        return name;
    }
}

Solution 9 - C#

In ASP.Net Core you can use two way:

First way: UseMemberCasing()
In StartUp.cs :

public void ConfigureServices(IServiceCollection services)
{
      services.AddControllersWithViews().AddNewtonsoftJson(opt =>
            {
                opt.UseMemberCasing();   // <-- add this
            });
}

Second way: ContractResolver
In StartUp.cs :

public void ConfigureServices(IServiceCollection services)
{
      services.AddControllersWithViews().AddNewtonsoftJson(opt =>
            {
                opt.SerializerSettings.ContractResolver = new DefaultContractResolver();   // <-- add this
            });
}

depends on your project maybe you used AddMvc() or AddControllers() insted of AddControllersWithViews().

If AddNewtonsoftJson not found, you should install Nuget pacage : Microsoft.AspNetCore.Mvc.NewtonsoftJson (link).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJaredView Question on Stackoverflow
Solution 1 - C#Martijn van HalenView Answer on Stackoverflow
Solution 2 - C#BRAHIM KamelView Answer on Stackoverflow
Solution 3 - C#pantonisView Answer on Stackoverflow
Solution 4 - C#Nate BarbettiniView Answer on Stackoverflow
Solution 5 - C#SimonView Answer on Stackoverflow
Solution 6 - C#Renato PereiraView Answer on Stackoverflow
Solution 7 - C#CharithJView Answer on Stackoverflow
Solution 8 - C#g.pickardouView Answer on Stackoverflow
Solution 9 - C#D.L.MANView Answer on Stackoverflow