Reputation: 85
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. *
Upvotes: 0
Views: 969
Reputation: 81
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:
Output: [ { "Id": 1, "Name": "America" }, { "Id": 2, "Name": "England" }, { "Id": 3, "Name": "CHINA" } ]
Example: https://dotnetfiddle.net/XVL2LI
Upvotes: 1
Reputation: 181
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;
}
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;
}
Upvotes: 2