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格式如下.

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

I'm expecting...

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

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

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

在关闭的机会,这是相关的行动和实例变量在控制器...

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

推荐答案

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

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

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

Json相关问答推荐

2020-12年草案中的Json列举模式

手动解开没有可编码的SON- Swift

我可以使用JQ来缩小数组中的json对象的范围吗?

在Reaction中从JSON文件中筛选数组

用于参考的Jolt变换

错误:在 NX 工作区中找不到模块../swagger.json

Jolt 转换数组对象并将某些字段移动到嵌套数组

遍历 JSON,检索父值

将请求中的数据推送到数组中

如何将该 JSON 解析为 Kotlin 类?

Scala - 在构建 Json 时无法删除 Key -> value "{}" 大括号的双引号

如何使用 Serde 使用顶级数组反序列化 JSON?

如何将任意 json 对象发布到 webapi

如何找出实际安装了哪个版本的 bower 包?

未捕获的类型错误:无法读取 null 的属性props

反序列化大型 json 对象的 JsonMaxLength 异常

对象序列化为 JSON(使用 Gson).如何在 UpperCamelCase 中设置字段名称?

将字符串映射到json对象的多种类型?

C++:使用 nlohmann json 从文件中读取 json 对象

NSURLRequest 中不支持的 URL