skip to Main Content

When i do a GET request to retrieve my list of Persons the enums(Title) get converted into integers:


class Person {

public Title PersonTitle{ get; set;}
public string Name { get; set;}


}

enum Title {
   STUDENT,
   TEACHER,
   DIRECTOR
}

Let’s Say we have the following situation:

Person first = new Person(){
  PersonTitle = Title.STUDENT,
  Name = "Dave"
}

this wil result in the following JSON:

[
 {
   "Name" : "Dave",
   "PersonTitle" : 1,
 }
]

How do I get the real value of the enum (STUDENT in this case) ?

3

Answers


  1. Chosen as BEST ANSWER

    The only code that had to be changed was:

    Before :

    public enum Title {
       STUDENT,
       TEACHER,
       DIRECTOR
    }
    

    After :

    using using System.Text.Json.Serialization;
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public enum Title {
       STUDENT,
       TEACHER,
       DIRECTOR
    }
    
    

    Now the response looks like:

    
    [
     {
       "Name" : "Dave",
       "PersonTitle" : "Student",
     }
    ]
    

  2. you can set the JsonConverterAttribute

    class Person {
    
    [JsonConverter(typeof(StringEnumConverter))]
    public Title PersonTitle{ get; set;}
    public string Name { get; set;}
    
    
    }
    

    Updating Enum with EnumMemberAttribute

    enum Title {
       [EnumMember(Value = "Student")]
       STUDENT,
       [EnumMember(Value = "Teacher")]
       TEACHER,
       [EnumMember(Value = "Director")]
       DIRECTOR
    }
    
    Login or Signup to reply.
  3. You need to add the adequate converter to the JSON serializer.

    System.Text.Json:

    Json.NET:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search