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

时间:2016-08-02 18:43:40

标签: c# .net angularjs json 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#模型

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返回属性名称而不更改它们?

8 个答案:

答案 0 :(得分:24)

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

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

答案 1 :(得分:14)

在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部分

答案 2 :(得分:5)

在ASP.NET Core中,JSON属性默认为camelCased(每this announcement)。

您可以通过替换

来禁用此功能
services.AddMvc();

services
    .AddMvc()
    .AddJsonOptions(opt => opt.SerializerSettings.ContractResolver
        = new DefaultContractResolver());
在您的Startup.cs文件中

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

DefaultContractResolver到位的情况下,属性名称将在JSON输出中逐字表示。不需要DataMember属性。

答案 3 :(得分:4)

对于那些需要有关Api Project中没有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;
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); ;
        }

答案 4 :(得分:4)

这是 .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);
}

答案 5 :(得分:2)

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

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

答案 6 :(得分:1)

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

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

答案 7 :(得分:0)

您必须更改默认情况下使用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; }
}