-3

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"
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
11738472
  • 184
  • 3
  • 22
  • 1
    Are you sure you are using [tag:json.net]? ASP.NET Core 3.0 and later use a different serializer, [tag:system.text.json]. See [Migrate from ASP.NET Core 2.2 to 3.0: Newtonsoft.Json (Json.NET) support](https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-5.0&tabs=visual-studio#newtonsoftjson-jsonnet-support) and [Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0?](https://stackoverflow.com/a/55666898/3744182). – dbc Dec 05 '20 at 13:53
  • 1
    [tag:system.text.json] uses a different attribute to control the serialized property name, [`JsonPropertyNameAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonpropertynameattribute). See [Converting newtonsoft code to System.Text.Json in .net core 3. what's equivalent of JObject.Parse and JsonProperty](https://stackoverflow.com/a/58273914/3744182). – dbc Dec 05 '20 at 13:56
  • 1
    If you are sure you are using Json.NET a [mcve] specifying your asp.net-core version and how you generated the output JSON would increase the chance we can help you. – dbc Dec 05 '20 at 13:57
  • @dbc Thanks for the response it worked, when gave the JsonPropertName instead of JsonProperty – 11738472 Dec 06 '20 at 12:35

1 Answers1

0

it worked, after following dbc's comment

public class ResponseJson
{
    [JsonPropertyName("StudentId")]
    public string StudentId { get; set; }
    [JsonPropertyName("dob")]
    public string DOB { get; set; }
    [JsonPropertyName("StudentName ")]
    public string StudentName { 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; }
}
11738472
  • 184
  • 3
  • 22