Home > Net >  How to get a friendly attribute name in API payload response?
How to get a friendly attribute name in API payload response?

Time:04-22

I want the get request to return a friendly names instead of the actual db column names. Is it possible?

my model class

public class Employee
    {
        public int EmployeeID { get; set; } 

        [DisplayName("First Name")]
        public string FirstName { get; set; } = string.Empty;

        public string LastName { get; set; } = string.Empty;

        public string Phone { get; set; } = string.Empty;

        public string Email { get; set; } = string.Empty;
}

payload that is generated. Note that the First Name is not changed

{
  "employeeID": 1501,
  "firstName": "Syed Omar",
  "lastName": "Khan",
  "phone": "9234567891",
  "email": "Syed [email protected]",
}

CodePudding user response:

If you want to change json property name of serialized class you can use corresponding attribute depending on json library used. For System.Text.Json it would be JsonPropertyNameAttribute. For Newtonsoft's Json.NET - JsonPropertyAttribute:

[JsonPropertyName("First Name")]
public string FirstName { get; set; } = string.Empty;

Or

[JsonProperty("First Name")]
public string FirstName { get; set; } = string.Empty;

CodePudding user response:

I got it by decorating the property name like below

[JsonPropertyName("Employee ID")]
public int EmployeeID { get; set; }

[JsonPropertyName("First Name")] 
public string FirstName { get; set; } = string.Empty;
  • Related