Last active
November 30, 2016 15:30
-
-
Save jltrem/b10b2cda184e99a1852061c5f36e96f3 to your computer and use it in GitHub Desktop.
C# used to create JSON for enums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using MyAppNamespace; | |
namespace MyAppNamespace.Util | |
{ | |
public class MyAppInfo | |
{ | |
public MyAppEnums Enums = new MyAppEnums(); | |
public static string ToJson() | |
{ | |
string json = JsonConvert.SerializeObject(new MyAppInfo()); | |
return json; | |
} | |
} | |
public class MyAppEnum<T> | |
{ | |
public int Val { get; set; } | |
public String Name { get; set; } | |
public String Descr { get; set; } | |
public MyAppEnum() | |
{ | |
} | |
public MyAppEnum(T val, string descr) | |
{ | |
Enum enumVal = Enum.Parse(typeof(T), val.ToString()) as Enum; | |
Val = Convert.ToInt32(enumVal); | |
Name = enumVal.ToString(); | |
Descr = descr; | |
} | |
} | |
public class MyAppEnums | |
{ | |
public List<MyAppEnum<FirstEnumeration>> FirstEnumeration = new List<MyAppEnum<FirstEnumeration>>(); | |
public List<MyAppEnum<SecondEnumeration>> SecondEnumeration = new List<MyAppEnum<SecondEnumeration>>(); | |
public List<MyAppEnum<ThirdEnumeration>> ThirdEnumeration = new List<MyAppEnum<ThirdEnumeration>>(); | |
public MyAppEnums() | |
{ | |
FirstEnumeration = MakeEnumList<FirstEnumeration>(); | |
SecondEnumeration = MakeEnumList<SecondEnumeration>(); | |
ThirdEnumeration = MakeEnumList<ThirdEnumeration>(); | |
} | |
private static List<MyAppEnum<T>> MakeEnumList<T>() | |
{ | |
var list = new List<MyAppEnum<T>>(); | |
foreach (var x in EnumHelper.GetValues<T>()) | |
{ | |
Enum enumVal = Enum.Parse(typeof(T), x.ToString()) as Enum; | |
list.Add(new MyAppEnum<T>(x, GetDescription(enumVal))); | |
} | |
return list; | |
} | |
/// <summary> | |
/// Retrieve the description on the enum, e.g. | |
/// [Description("Bright Pink")] | |
/// BrightPink = 2, | |
/// Then when you pass in the enum, it will retrieve the description | |
/// </summary> | |
/// <param name="en">The Enumeration</param> | |
/// <returns>A string representing the friendly name</returns> | |
private static string GetDescription(Enum en) | |
{ | |
Type type = en.GetType(); | |
MemberInfo[] memInfo = type.GetMember(en.ToString()); | |
if (memInfo != null && memInfo.Length > 0) | |
{ | |
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); | |
if (attrs != null && attrs.Length > 0) | |
{ | |
return ((DescriptionAttribute)attrs[0]).Description; | |
} | |
} | |
return en.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment