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

12

69

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?

Normannormand answered 2/8, 2016 at 18:43 Comment(1)
this is a known change in RTM github.com/aspnet/Announcements/issues/194Charger
V
26

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.

Vincentvincenta answered 2/8, 2016 at 18:54 Comment(0)
E
65

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

Esmeraldaesmerelda answered 27/9, 2019 at 12:56 Comment(3)
Excellent working solution for .Net Core 3. The PropertyNamingPolicy is camelCase by default and set it to null makes it working like charm. Thanks a lot ;)Hailstone
Thanks Martijn. Question: For legacy reasons, I need some controllers in my .NET Core 3 API to return camel case and others pascal case. So a mix of both worlds. Is there any way to configure this on a controller level ?Vesuvian
Yes, in your controller you may use: return new JsonResult(clientDTO, new JsonSerializerOptions { PropertyNamingPolicy = null, // switch off camelcasing by default WriteIndented = true } );Undertook
S
55

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;
                } ;
        }
Sweetening answered 25/11, 2019 at 13:12 Comment(3)
This was indead the answer for me well done in getting this one it had to be the PropetyNamingPolicy this now has the expected result thanks.Reveal
A parenthesis is missing just before the semicolon. services.AddControllers().AddJsonOptions(jsonOptions => { jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null; } );Singsong
worked for me in asp.net 6 and 7Needlepoint
K
46

For Asp.Net Core 3.1 using the NewtonSoft.Json

services.AddControllers()
        .AddNewtonsoftJson(options =>
        {
            options.UseMemberCasing();
        });
Kalgan answered 19/3, 2020 at 8:8 Comment(2)
also requires nuget package Microsoft.AspNetCore.Mvc.NewtonsoftJson to be able to use that optionMelanosis
This is the correct answer for Newtonsoft/.NET Core 5 as well, and worked with services.AddControllersWithViews() in our hybrid environment.Supplicatory
V
26

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.

Vincentvincenta answered 2/8, 2016 at 18:54 Comment(0)
I
20

Here is the answer for .net 5 :

https://learn.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);
}
Intransigence answered 24/3, 2021 at 1:44 Comment(1)
This worked well and since it's documented on .Net 6 also I went with this solution.Incriminate
S
4

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

services.AddMvc()
.AddJsonOptions(jsonOptions => jsonOptions.UseMemberCasing())
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
Subjoinder answered 24/1, 2020 at 20:41 Comment(1)
With the technology being upgraded very often, and when people finding for the perfect answers/solutions, a better one, we should allow the SO to mark them somehow. In that perspective, this is the best answer at the moment for .net core web api 2x / 3. The question is not specifically mentioning the .net core fx version so i'd assume the answers should go on top based on the closest match to the current version.Rupe
D
2

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).

Deteriorate answered 29/11, 2021 at 21:0 Comment(0)
J
2

In .NET 6 I used:

builder.Services.AddControllersWithViews()
.AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = null);
Julissa answered 6/12, 2022 at 14:57 Comment(0)
U
1

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; }
}
Unicorn answered 13/1, 2019 at 1:0 Comment(0)
S
1

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;
    }
}
Stanton answered 19/10, 2020 at 14:18 Comment(2)
Can we make this policy a controller specific? or even action method specific?Cabman
@Nour, you probably have your answer by now but here's what I found (based on .Net 6) documented at learn.microsoft.com/en-us/aspnet/core/web-api/advanced/… public IActionResult Get() => new JsonResult( _todoItemStore.GetList(), new JsonSerializerOptions { PropertyNamingPolicy = null });Incriminate
J
0

With .Net Core 6

 builder.Services.AddControllers()
   .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy 
           = JsonNamingPolicy.CamelCase;
    });
Jase answered 12/4, 2023 at 0:40 Comment(0)
O
0

Try below code to prevent camelcase conversion.

namespace System.Text.Json;
public IActionResult Insert(Model value)
{
  return Ok(JsonSerializer.Serialize(value));
}
Oscitancy answered 15/6, 2023 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.