Skip to content

Instantly share code, notes, and snippets.

@jltrem
Last active November 30, 2016 15:30
Show Gist options
  • Save jltrem/b10b2cda184e99a1852061c5f36e96f3 to your computer and use it in GitHub Desktop.
Save jltrem/b10b2cda184e99a1852061c5f36e96f3 to your computer and use it in GitHub Desktop.
C# used to create JSON for enums
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