繁体   English   中英

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

[英]How to turn off or handle camelCasing in JSON response 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}
]

我期待着...

[
 {"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}
]

基于C# model...

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; }
    }
}

我什至用[DataMember(Name = "Id")]装饰属性只是为了确保它仍然没有关系。

在偶然的情况下,它与 controller 中的 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;
}

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

在 Asp.Net Core 3.0 中,有些事情发生了变化。 对于camelCase,什么都不做。 对于 PascalCase 或其他设置样式使用。

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

在 Startup.cs ConfigureServices 部分

对于那些需要有关 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;
                } ;
        }

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

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

在 ASP.NET Core <3.0 中,JSON 属性默认为驼峰格式(根据本公告)。

您可以通过替换来禁用它

services.AddMvc();

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

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

使用DefaultContractResolver后,属性名称将在 JSON 输出中逐字表示。 不需要DataMember属性。

这是 .net 5 的答案:

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

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

默认格式是驼峰式大小写。 以下突出显示的代码设置 PascalCase 格式

C#

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

Asp.Net.Core 2.2 中的另一个解决方案如下:

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

您必须更改默认使用驼峰命名的 DefaultContractResolver。 只需将NamingStatergy设置为null

这应该在StartUp.ConfirgureService完成,如下所示。

  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;
                }
            });
    }

选项 2

如下使用 JSonProperty。

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; }
}

我正在使用以下解决方案,因为

  • a) 我更喜欢使用System.Text.Json序列化器中内置的 .Net Core 和
  • b) 我不想依赖jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;未记录的内部行为jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null; .

.

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

在哪里:

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;
    }
}

在 ASP.Net Core 中,您可以使用两种方式:

第一种方式: UseMemberCasing()
StartUp.cs

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

第二种方式: ContractResolver
StartUp.cs

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

取决于您的项目,也许您使用AddMvc()AddControllers() AddMvc() AddControllersWithViews()

如果未找到AddNewtonsoftJson ,则应安装 Nuget 包: Microsoft.AspNetCore.Mvc.NewtonsoftJson链接)。

在 .NET 6 中我使用了:

builder.Services.AddControllersWithViews().AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM