如何在JSON响应ASP.NET Core中关闭或处理camelCasing? [英] How to turn off or handle camelCasing in JSON response ASP.NET Core?

查看:67
本文介绍了如何在JSON响应ASP.NET Core中关闭或处理camelCasing?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过ASP.NET Core / Web API / Angular 2上的WintellectNOW课程进行学习。我已经实现了API部分,但是由于某种原因,返回的JSON的变量名都被小写了。

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.

返回的JSON格式如下...

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

我希望...

[
 {"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#模型。

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

我甚至还用 [DataMember(Name = Id)] 只是为了确保它仍然没有关系。

I even went as far as decorating the properties with [DataMember(Name = "Id")] just to make sure and it still didn't matter.

在偶然的机会上,它与控制器中的Action和instance变量有关...

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

如何关闭camelCase功能,以便ASP.NET Core返回

How do I turn off the camelCase functionality, so that ASP.NET Core returns the property names without changing them?

推荐答案

在ASP.NET Core< 3.0中,默认情况下驼峰JSON属性(按< a href = https://github.com/aspnet/Announcements/issues/194 rel = nofollow noreferrer>此公告)。

In ASP.NET Core <3.0, JSON properties are camelCased by default (per this announcement).

您可以通过替换

services.AddMvc();

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

在Startup.cs文件中。您必须使用Newtonsoft.Json.Serialization添加到文件顶部。

in your Startup.cs file. You'll have to add using Newtonsoft.Json.Serialization; to the top of the file.

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

With the DefaultContractResolver in place, the property names will be represented verbatim in the JSON output. No need for DataMember attributes.

这篇关于如何在JSON响应ASP.NET Core中关闭或处理camelCasing?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆