Showing posts with label C# Json Enum. Show all posts
Showing posts with label C# Json Enum. Show all posts

Monday, 23 January 2023

Creating a json string representing enum names and values in C#

A short blog post here demonstrating how to create a JSON string showing enum names and values for an enum in C#, simple stuff! From Linqpad 7:

void Main()
{
	var jsonEnum = EnumUtil.GenerateJsonForEnum<PasientOvertattEnum>();
	jsonEnum.Dump();	
}

public static class EnumUtil
{

	/// <summary>
	/// Generates a json string (array) for enum values
	/// Checked that it gives valid json array string here : https://jsonlint.com/
	/// </summary>
	public static string GenerateJsonForEnum<TEnum>()
	 where TEnum : struct, IConvertible
	{
		var enumItems = new List<object>();
		var sb = new StringBuilder();
		sb.AppendLine("[\n");
		bool isEnumValueFound = false;
		foreach (var enumValue in Enum.GetValues(typeof(TEnum)))
		{
			sb.AppendLine($@"	{{	""Name"": ""{enumValue}"", ""Value"": ""{(int)enumValue}""	}},");
			isEnumValueFound = true;
		}
		if (isEnumValueFound)
		{
			sb.Remove(sb.Length - 3, 1);
		}
		sb.AppendLine("\t]");
		return sb.ToString();
	}
}



This gives the following sample json string when testing:


[

  {  "Name": "Velgverdi", "Value": "0"  },
  {  "Name": "AkershusUniversitetssykehusHF", "Value": "1"  },
  {  "Name": "DiakonhjemmetSykehusAS", "Value": "2"  },
  {  "Name": "FinnmarkssykehusetHF", "Value": "3"  },
  {  "Name": "HaraldsplassDiakonaleSykehusAS", "Value": "4"  },
  {  "Name": "HelgelandssykehusetHF", "Value": "5"  },
  {  "Name": "HelseBergenHF", "Value": "6"  },
  {  "Name": "HelseFonnaHF", "Value": "7"  },
  {  "Name": "HelseFordeHF", "Value": "8"  },
  {  "Name": "HelseMoreogRomsdalHF", "Value": "9"  },
  {  "Name": "HelseNordTrondelagHF", "Value": "10"  },
  {  "Name": "HelseStavangerHF", "Value": "11"  },
  {  "Name": "LovisenbergDiakonaleSykehusAS", "Value": "12"  },
  {  "Name": "NordlandssykehusetHF", "Value": "13"  },
  {  "Name": "OsloUniversitetssykehusHF", "Value": "14"  },
  {  "Name": "SandvikaNevrosenter", "Value": "15"  },
  {  "Name": "StOlavshospitalHF", "Value": "16"  },
  {  "Name": "SykehusetiVestfoldHF", "Value": "17"  },
  {  "Name": "SykehusetInnlandetHF", "Value": "18"  },
  {  "Name": "SykehusetTelemarkHF", "Value": "19"  },
  {  "Name": "SykehusetOstfoldHF", "Value": "20"  },
  {  "Name": "SorlandetsykehusHF", "Value": "21"  },
  {  "Name": "UniversitetssykehusetNordNorgeHF", "Value": "22"  },
  {  "Name": "VestreVikenHF", "Value": "23"  },
  {  "Name": "Utenlands", "Value": "24"  },
  {  "Name": "Ukjent", "Value": "25"  }
  ]




The JSON string above has been tested and validated okay against : https://jsonlint.com/ So if you need to show the data contents of an enum into a Json, this is a simple way of doing this.