JSON 응답 ASP에서 camelCasing을 끄거나 처리하는 방법.NET Core?
Wintelect를 검색 중입니다.ASP 코스입니다.NET Core/Web API/Angular 2.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")]혹시 모르니까 그래도 상관없었어
경우에 따라서는 컨트롤러의 액션 및 인스턴스 변수와 관련이 있습니다.
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;
}
ASP를 위해 camel Case 기능을 끄려면 어떻게 해야 합니까?NET Core에서 속성 이름을 변경하지 않고 반환하시겠습니까?
ASP.Net Core 3.0에서는 몇 가지 사항이 변경되었습니다.camel Case의 경우 개봉 후 바로 사용할 수 있습니다.PascalCase 또는 다른 세트 스타일 사용.
services.AddMvc(setupAction=> {
setupAction.EnableEndpointRouting = false;
}).AddJsonOptions(jsonOptions =>
{
jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
Startup.cs 의 [Configure Services]섹션에서
Mvc 서비스가 없는 API 프로젝트 내의 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;
} ;
}
ASP용Net Core 3.1 (Newton Soft 사용)제이슨
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.UseMemberCasing();
});
ASP.NET Core < 3.0 에서는, JSON 속성은 디폴트로 camelCased 입니다(이 아나운스먼트에 따라서).
이 기능을 비활성화하려면
services.AddMvc();
와 함께
services
.AddMvc()
.AddJsonOptions(opt => opt.SerializerSettings.ContractResolver
= new DefaultContractResolver());
Startup.cs 파일을 참조해 주세요.를 추가해야 합니다.using Newtonsoft.Json.Serialization;파일 맨 위로 이동합니다.
를 사용하여DefaultContractResolver속성명은 JSON 출력에 말 그대로 표시됩니다.필요 없다DataMember특성.
다음은 .net 5에 대한 답변입니다.
https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0
시스템을 설정합니다.Text.Json 기반 포메터의 시스템 기능.Text.Json 기반 포메터는 Microsoft를 사용하여 구성할 수 있습니다.AspNetCore.MVC.Json 옵션Json Serializer 옵션
기본 포맷은 camel Case 입니다. 다음 강조 표시된 코드는 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);
ASP.Net Core 에서는, 다음의 2개의 방법을 사용할 수 있습니다.
첫 번째 방법: Use Member Casing()
인StartUp.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddNewtonsoftJson(opt =>
{
opt.UseMemberCasing(); // <-- add this
});
}
두 번째 방법: Contract Resolver
인StartUp.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddNewtonsoftJson(opt =>
{
opt.SerializerSettings.ContractResolver = new DefaultContractResolver(); // <-- add this
});
}
프로젝트에 따라 다르겠지만AddMvc()또는AddControllers()을 주입한.AddControllersWithViews().
한다면AddNewtonsoftJson를 찾을 수 없습니다.Nuget pacage : Microsoft 를 인스톨 할 필요가 있습니다.AspNetCore.MVC.NewtonsoftJson(링크)
기본적으로 camelCase를 사용하는 DefaultContractResolver를 변경해야 합니다. Just set the 설정만 하면 됩니다.NamingStatergy as ~하듯이null.
작 조 은 the, this should be?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) a) I prefer using the .a) 를 사용하는 것이 좋습니다.Net 코어 장에서 만들어진 Net 코어 내)
System.Text.Json및 serializer - 되어 있지 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;
}
}
.NET 6에서는 다음을 사용했습니다.
builder.Services.AddControllersWithViews().AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = null);
언급URL : https://stackoverflow.com/questions/38728200/how-to-turn-off-or-handle-camelcasing-in-json-response-asp-net-core
'source' 카테고리의 다른 글
| useEffect의 예상 수익은 무엇에 사용됩니까? (0) | 2023.03.13 |
|---|---|
| Node.js Typescript 프로젝트 TypeError [ERR_UNKNOWN_FILE_EXTENTION]: /app/src/App.ts의 알 수 없는 파일 확장자 ".ts"를 실행할 수 없습니다. (0) | 2023.03.13 |
| Oracle user_contraints 테이블의 contraint_type 열에 있는 문자 코드는 무엇을 나타냅니까? (0) | 2023.03.13 |
| API를 사용하여 Wikipedia 검색 (0) | 2023.03.13 |
| JavaScript 개체를 JSON 문자열로 직렬화 (0) | 2023.03.13 |