Home > Net >  How to convert Enum to Json object with Header in C#
How to convert Enum to Json object with Header in C#

Time:03-05

Here's what I've done so far

public enum TCountryNames
{
  [Display(Name="America")]
  cnUSA = 1,
  [Display(Name="England")]
  cnUK,
  [Display(Name="CHINA")]
  cnCHN
}

public class MyClass
{
  public static List<KeyValuePair<string, int>> GetEnumList()
    {
        var list = new List<KeyValuePair<string, int>>();
        foreach (var e in Enum.GetValues(typeof(TCountryNames)))
        {
            list.Add(new KeyValuePair<string, int>(e.ToString(), (int)e));
        }
        return list;
    }
}

Result: [cnUSA,1] with total count 3 and without header

The result i want is [{"Id":1,"Name":"America"},{"Id":2,"Name":"England"}]

I've tried [JsonConverter(typeof(StringEnumConverter))] public TCountryNames Names{ get; set; }

I've also tried converting enum to array list var names = Enum.GetValues(typeof(TCountryNames)); ArrayList arrLst = new ArrayList() { names }; but both of them doesn't seems to be working.

*Any help will be appreciated. Thank You in Advance. *

CodePudding user response:

  1. If you don't want to add new class

     public static List<Dictionary<string, object>> GetEnumList()
     {
         var list = new List<Dictionary<string, object>>();
         foreach (var e in Enum.GetValues(typeof(TCountryNames)))
         {
             list.Add(new Dictionary<string, object> { { "Id", (int)e }, { "Name", e.ToString() } });
         }
         return list;
     }
    
  2. Define a model for serialization

     public class EnumData
     {
         public int Id { get; set; }
         public string Name { get; set; }
     }
    
     public static List<EnumData> GetEnumList()
     {
         var list = new List<EnumData>();
         foreach (var e in Enum.GetValues(typeof(TCountryNames)))
         {
             list.Add(new EnumData { Id = (int)e, Name = e.ToString() });
         }
         return list;
     }
    

CodePudding user response:

For get display name value you should use System.Reflection. And then you could do this in simple way:

   public enum TCountryNames
    {
        [Display(Name = "America")]
        cnUSA = 1,
        [Display(Name = "England")]
        cnUK,
        [Display(Name = "CHINA")]
        cnCHN
    }

public class EnumData
{
    public int Id { get; set; }
    public string? Name { get; set; }
}

public class MyClass
{
    public static List<EnumData> GetEnumList()
    {
        var list = new List<EnumData>();
        foreach (var e in Enum.GetValues(typeof(TCountryNames)))
        {
            list.Add(new EnumData
            { 
                Id = (int)e, 
                Name = e.GetType()
                    .GetMember(e.ToString())
                    .First()?
                    .GetCustomAttribute<DisplayAttribute>()?
                    .GetName()
            });
        }
        return list;
    }
}

So to clarify:

  • you create loop foreach enum
  • take id by casting
  • take name using reflaction - I added all needed protection against null exception

Output: [ { "Id": 1, "Name": "America" }, { "Id": 2, "Name": "England" }, { "Id": 3, "Name": "CHINA" } ]

Example: https://dotnetfiddle.net/XVL2LI

  • Related