的Json属性空 - ASP.NET核心
问题描述:
我有以下型号的Json属性空 - ASP.NET核心
public class SocioEconomicStudy : BaseModel
{
public string Folio { get; set; }
public string Craft { get; set; }
public string RequestType {get;set;}
}
我送以下JSON
{
"folio" : "folio",
"craft" : "craft,
"request_type": "request_type"
}
但与下划线收到的属性为null,我已经试过骆驼案件帕斯卡案件,但只有小写+下划线是没有下划线的属性工作。
控制器的方法:
[HttpPost]
public void Post([FromBody] SocioEconomicStudy study)
{
var cancellationToken = new CancellationToken();
_logger.LogInformation((study != null).ToString());
_context.SocioEconomicStudyRepository.AddAsync(study, cancellationToken);
}
因此,只有没有下划线的属性依然存在,如何解决这个任何想法?
答
加入以下Startup.cs
解决我的问题
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
});
属性现在它接受camelCase密钥
答
对于那些不符合命名规则,你可以添加JsonProperty
属性,你的情况你的模型应该像这样
public class SocioEconomicStudy : BaseModel
{
public string Folio { get; set; }
public string Craft { get; set; }
[JsonProperty("request_type")]
public string RequestType { get; set; }
}
+0
谢谢,但是如果我的模型改变了,或者我需要更多模型,我还需要使用多个单词注释每个属性。 –
+0
是的,您需要注释每个属性或更改前端部分以发送名为camel case的属性 –
你使用什么json serializer? –
@RubenVardanyan我正在使用默认序列化程序 –
请参阅下面的回答 –