【问题标题】:How to turn off or handle camelCasing in JSON response ASP.NET Core?如何在 JSON 响应 ASP.NET Core 中关闭或处理 camelCasing?
【发布时间】:2016-12-08 06:23:48
【问题描述】:

我正在学习关于 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#模型的...

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")] 来装饰房产只是为了确保它仍然没关系。

在偶然的情况下,它与控制器中的 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 返回属性名称而不更改它们?

【问题讨论】:

标签: c# .net angularjs json asp.net-core


【解决方案1】:

在 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 配置服务部分

【讨论】:

  • .Net Core 3 的出色工作解决方案。PropertyNamingPolicy 默认为驼峰式,将其设置为 null 使其工作起来像魅力一样。非常感谢;)
  • 谢谢 Martijn。问:由于遗留原因,我的 .NET Core 3 API 中需要一些控制器来返回骆驼大小写和其他帕斯卡大小写。所以两个世界的混合。有没有办法在控制器级别上配置它?
  • 是的,在你的控制器中你可以使用: return new JsonResult(clientDTO, new JsonSerializerOptions { PropertyNamingPolicy = null, // 默认关闭驼峰式 WriteIndented = true } );
【解决方案2】:

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

【讨论】:

  • 这对我来说是一个很好的答案,它必须是 PropetyNamingPolicy,现在有了预期的结果,谢谢。
【解决方案3】:

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

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

【讨论】:

  • 还需要 nuget 包 Microsoft.AspNetCore.Mvc.NewtonsoftJson 才能使用该选项
  • 这也是 Newtonsoft/.NET Core 5 的正确答案,并且在我们的混合环境中与 services.AddControllersWithViews() 一起使用。
【解决方案4】:

在 ASP.NET Core this announcement)。

您可以通过替换来禁用此功能

services.AddMvc();

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

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

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

【讨论】:

    【解决方案5】:

    这是 .net 5 的答案:

    https://docs.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);
    }
    

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

      • 随着技术的不断升级,当人们寻找完美的答案/解决方案时,我们应该允许 SO 以某种方式对其进行标记。从这个角度来看,这是目前 .net core web api 2x / 3 的最佳答案。问题没有具体提到 .net core fx 版本,所以我假设答案应该根据最接近的匹配放在首位到当前版本。
      【解决方案7】:

      您必须更改默认使用 camelCase 的 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; }
      }
      

      【讨论】:

        【解决方案8】:

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

        • a) 我更喜欢使用内置于System.Text.Json 序列化程序的.Net Core 和
        • b) 我不想依赖未记录的内部行为 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;
            }
        }
        

        【讨论】:

        • 我们可以将此策略设为特定于控制器吗?甚至具体的操作方法?
        【解决方案9】:

        在 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() insted of AddControllersWithViews()

        如果找不到AddNewtonsoftJson,你应该安装Nuget包:Microsoft.AspNetCore.Mvc.NewtonsoftJson (link)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-26
          • 1970-01-01
          • 2020-01-25
          • 2014-09-28
          相关资源
          最近更新 更多