【发布时间】:2020-12-05 06:06:42
【问题描述】:
在我的 API 中,我使用 automapper 映射到模型,它可以很好地将实体映射到模型,但我想将 PropertyNames 添加到模型中。我使用了 Json.net 的 JsonProperty,但这不是例外。
下面是DTO类
public class StudentModel
{
[JsonProperty("Admission Number")] public string StudentId { get; set; }
[JsonProperty("Date of Birth")] public string DOB { get; set; }
[JsonProperty("Name")] public string StudentName { get; set; }
}
下面是实体类
public class StudentEntity
{
public string StudentId { get; set; }
public DateTime DOB { get; set; }
public string StudentName { get; set; }
}
这样的映射mappingProfile.CreateMap<StudentEntity, StudentModel>()
映射器是:_mapper.Map<StudentEntity, StudentModel>(entity)).ToList();
但我没有在响应中获得 JSON 属性
这样的输出
{
"studentId": "30112020",
"dOB": "01-01-2020 12:00 AM",
"studentName": "rom"
}
但我想变成这样
{
"Admission Number": "30112020",
"Date of Birth": "01-01-2020 12:00 AM",
"Name": "rom"
}
【问题讨论】:
-
你确定你使用的是json.net吗? ASP.NET Core 3.0 及更高版本使用不同的序列化程序system.text.json。见Migrate from ASP.NET Core 2.2 to 3.0: Newtonsoft.Json (Json.NET) support 和Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0?。
-
如果您确定您使用的是 Json.NET,minimal reproducible example 指定您的 asp.net-core 版本以及生成输出 JSON 的方式将增加我们为您提供帮助的机会。
-
@dbc 感谢它的响应,当给出 JsonPropertName 而不是 JsonProperty 时
标签: c# .net-core json.net automapper