【问题标题】:how to set the jsonproperty for property names to the dto while using automapper?如何在使用自动映射器时将属性名称的 jsonproperty 设置为 dto?
【发布时间】: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"
}

【问题讨论】:

标签: c# .net-core json.net automapper


【解决方案1】:

在听了 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; }
}

【讨论】:

    猜你喜欢
    • 2020-06-11
    • 2015-03-19
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多