how to set the jsonproperty for property names to the dto while using automapper?

In my API I’m using automapper for mapping to model, and it is finely mapping the entity to model, but I want to add PropertyNames to the model. I used Json.net’s JsonProperty but this is not working as excepted.

the below is the 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; }
}

the below is the entity class

public class StudentEntity
{
public string StudentId { get; set; }
public DateTime DOB { get; set; }
public string StudentName { get; set; }
}

the mapping like this mappingProfile.CreateMap<StudentEntity, StudentModel>() and the mapper is: _mapper.Map<StudentEntity, StudentModel>(entity)).ToList();

but I’m not getting the JSON property in the response

the output like this

{
"studentId": "30112020",
"dOB": "01-01-2020 12:00 AM",
"studentName": "rom"
}

but I want to get like this

{
"Admission Number": "30112020",
"Date of Birth": "01-01-2020 12:00 AM",
"Name": "rom"
}

Thanks in advance

Answer

it worked, after following dbc’s comment

public class ResponseJson
{
    [JsonPropertyName("status")]
    public bool Status { get; set; }
    [JsonPropertyName("message")]
    public string Message { get; set; }
    [JsonPropertyName("Log_id")]
    public string LogId { get; set; }
    [JsonPropertyName("Log_status")]
    public string LogStatus { get; set; }

    public string FailureReason { get; set; }
}

instead of

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; }
}

Leave a Reply

Your email address will not be published. Required fields are marked *