如何在JSON响应ASP.NET Core中关闭或处理camelCasing?

Jar*_*red 11 .net c# json angularjs asp.net-core

我在ASP.NET Core/Web API/Angular 2上运行WintellectNOW课程.我已经实现了API部分,但无论出于何种原因,返回的JSON的变量名称都是小写的.

返回的JSON格式为...

[
 {"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}
]
Run Code Online (Sandbox Code Playgroud)

我期待着...

[
 {"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}
]
Run Code Online (Sandbox Code Playgroud)

基于...的C#模型

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

我甚至为装饰物业而[DataMember(Name = "Id")]努力确保它仍然无关紧要.

关闭机会,它与控制器中的Action和实例变量相关...

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;
}
Run Code Online (Sandbox Code Playgroud)

如何关闭camelCase功能,以便ASP.NET Core返回属性名称而不更改它们?

BRA*_*mel 40

对于那些需要有关 Api 项目中没有 Mvc 服务的 PascalCase 的解决方案的人,您应该在 AddControllers 服务之后添加它

 // 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;
                } ;
        }
Run Code Online (Sandbox Code Playgroud)

  • 这确实是我的答案,它必须是 PropetyNamingPolicy,现在已经达到了预期的结果,谢谢。 (2认同)

pan*_*nis 36

对于使用 NewtonSoft.Json 的 Asp.Net Core 3.1

services.AddControllers()
        .AddNewtonsoftJson(options =>
        {
            options.UseMemberCasing();
        });
Run Code Online (Sandbox Code Playgroud)

  • 还需要 nuget 包 Microsoft.AspNetCore.Mvc.NewtonsoftJson 才能使用该选项 (5认同)

Sim*_*mon 19

这是 .net 5 的答案:

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

配置基于 System.Text.Json 的格式化程序 基于 System.Text.Json 的格式化程序的功能可以使用 Microsoft.AspNetCore.Mvc.JsonOptions.JsonSerializerOptions 配置。

默认格式为驼峰命名法。以下突出显示的代码设置 PascalCase 格式

C#

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
            .AddJsonOptions(options => 
               options.JsonSerializerOptions.PropertyNamingPolicy = null);
}
Run Code Online (Sandbox Code Playgroud)


小智 12

在Asp.Net Core 3.0中,有些事情已经改变。对于camelCase,什么也不要做。对于PascalCase或其他设置样式使用。

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

在Startup.cs ConfigureServices部分中

  • 是的,在您的控制器中,您可以使用: return new JsonResult(clientDTO, new JsonSerializerOptions { PropertyNamingPolicy = null, // 默认关闭驼峰式命名 WriteIndented = true } ); (2认同)

Nat*_*ini 10

在ASP.NET Core中,JSON属性默认为camelCased(根据此声明).

您可以通过替换来禁用它

services.AddMvc();
Run Code Online (Sandbox Code Playgroud)

services
    .AddMvc()
    .AddJsonOptions(opt => opt.SerializerSettings.ContractResolver
        = new DefaultContractResolver());
Run Code Online (Sandbox Code Playgroud)

在您的Startup.cs文件中.您必须添加using Newtonsoft.Json.Serialization;到文件的顶部.

随着DefaultContractResolver到位,属性名称将被逐字在JSON输出表示.不需要DataMember属性.