Serialize Enum as DisplayName or EnumMember Value
Asked Answered
Q

0

2

I have an enum declared in c#. I have a Display Name/ EnumMember value annotation and Student Class. I'm using asp.net core 2.2+ version with Odata.

[DataContract]
Public Class Library 
{
 public int Id {get;set;}

 [DataMember(Name="Book_Name")]
 public BookNameEnum BookName {get; set;}

}

[DataContract]
JsonConverter[typeof(StringEnumConverter)]
public enum BookNameEnum 
{
  [Display(Name ="John Wick"), EnumMember(value="John Wick")]
  JohnWick = 1,
  [Display(Name ="John Snow"), EnumMember(value="John Snow")]
  JohnSnow = 2,
  [Display(Name ="Jack Sparrow"), EnumMember(value="Jack Sparrow")]
  JackSparrow = 3,
  [Display(Name ="Jorder M"), EnumMember(value="Jorder M")]
  JorderM = 4
}

I want to achieve the desired result as below in my postman API call.

{
   "Id" : 10001,
   "Book_Name": "John Wick" /*Display Name or EnumMember Value*/
},
{
   "Id" : 10001,
   "Book_Name": "John Snow" /*Display Name or EnumMember Value*/
},
{
   "Id" : 10001,
   "Book_Name": "Jack Sparrow" /*Display Name or EnumMember Value*/
}

But currently, I'm getting the below result which is just the enum identifier as a string, which isn't expected.

{
   "Id" : 10001,
   "Book_Name": "JohnWick" // as declared in enum against value 
},
{
   "Id" : 10001,
   "Book_Name": "JohnSnow" // as declared in enum against value 
},
{
   "Id" : 10001,
   "Book_Name": "JackSparrow" // as declared in enum against value 
}
Quadrivial answered 2/6, 2020 at 11:8 Comment(2)
I guess, you should write your own converter for thatVotary
@PavelAnikhouski Yes, I've done that. I have overridden various methods of the JsonConverter and tried to handle this but had no luck.Quadrivial

© 2022 - 2024 — McMap. All rights reserved.