0

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) ?

dbc
  • 104,963
  • 20
  • 228
  • 340
schweppes0x
  • 182
  • 1
  • 13
  • 1
    `public Type { get; set;}` you missing something here?? – huMpty duMpty Oct 26 '21 at 13:26
  • I forgot the name of the property but that's not the problem. It's edited now – schweppes0x Oct 26 '21 at 13:29
  • 1
    An enum *is* an integer. An enum value is By default enums are serialized as integers. Both JSON.NET and System.Text.Json can be configured to serialize them using their tag names instead. Which one are you using? For System.Text.Json check [Enums as strings](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-customize-properties?pivots=dotnet-5-0#enums-as-strings) – Panagiotis Kanavos Oct 26 '21 at 13:32
  • When i do a Get request, my method sends a list with those persons. – schweppes0x Oct 26 '21 at 13:47

3 Answers3

2

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",
 }
]
schweppes0x
  • 182
  • 1
  • 13
0

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
}
huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
0

You need to add the adequate converter to the JSON serializer.

System.Text.Json:

Json.NET:

Ivo
  • 396
  • 1
  • 9