如何在使用自动映射器时将 属性 名称的 json属性 设置为 dto?
how to set the jsonproperty for property names to the dto while using automapper?
在我的 API 中,我使用自动映射器映射到模型,它可以很好地将实体映射到模型,但我想将 PropertyNames 添加到模型。我使用了 Json.net's JsonProperty 但这并没有正常工作。
下面是DTO class
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; }
}
下面是实体class
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"
}
在遵循 dbc 的评论后,它起作用了
public class ResponseJson
{
[JsonPropertyName("StudentId")]
public string StudentId { get; set; }
[JsonPropertyName("dob")]
public string DOB { get; set; }
[JsonPropertyName("StudentName ")]
public string StudentName { get; set; }
}
而不是
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; }
}
在我的 API 中,我使用自动映射器映射到模型,它可以很好地将实体映射到模型,但我想将 PropertyNames 添加到模型。我使用了 Json.net's JsonProperty 但这并没有正常工作。
下面是DTO class
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; }
}
下面是实体class
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"
}
在遵循 dbc 的评论后,它起作用了
public class ResponseJson
{
[JsonPropertyName("StudentId")]
public string StudentId { get; set; }
[JsonPropertyName("dob")]
public string DOB { get; set; }
[JsonPropertyName("StudentName ")]
public string StudentName { get; set; }
}
而不是
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; }
}