0

This question is related, but IMHO not identical to

Whilst testing, I've also stumbled across this culprit LinqPad which made my life difficult: Why does LINQPad dump enum integer values as strings?

Now, my actual question: My application (in particular SyncFusion component datasources, such as MultiSelect) requires enumerations in JSON format, e.g. something like this:

[ {"Id":0,"Name":"Unknown"},{"Id":1,"Name":"Open"},{"Id":2,"Name":"Closed"},{"Id":3,"Name":"Approve"} ]

UPDATE As dbc pointed out, my question may not have been clear enough. I do not want to serialize one entry of the enumeration, but the whole struct. The JSON could then be used for a data source in Javascript, e.g. for a , simplified: <option value=0>Unknown</option> <option value=1>Open</option> etc

The JSON object is identical to an Enum in a namespace (with the exception that I have given the a property name to the Key and Value of each entry:

public enum ListOptions
{
    Unknown = 0,
    Open = 1,
    Closed = 2,
    Approve = 3
}

I've struggled with Enums, all the other approaches such as specifying a Json StringConverter etc did't yield all options in an array, so I ended up using Linq. My View Model now has a string property like this:

public string CrewListOption => JsonConvert.SerializeObject(Enum.GetValues(typeof(ListOptions))
        .Cast<int>()
        .Select(e => new { Id = (int)  e, Name = typeof(ListOptions).GetEnumName(e) }));

Given that I'm pretty much a beginner with ASP.Net Core, I find it hard to believe that this should be a good solution. Yet I find it hard to find straight-forward better examples of the same thing.

I'd appreciate it if you might be able to help me improve this, and make it potentially more generically useful to "export" whole enumerations to JSON.

Here's the full LinqPad (where Newtonsoft.Json is imported from GAC):

void Main()
{   
    Enum.GetValues(typeof(ListOptions)).Cast<int>().Select(e => new { Id = e, Name = (ListOptions) e } ).Dump(); // these are identical, except for the typeof()
    Enum.GetValues(typeof(ListOptions)).Cast<int>().Select(e => new { Id = (int)  e, Name = typeof(ListOptions).GetEnumName(e) }).Dump(); // is typeof(MyEnumType) better?
    string JsonString = JsonConvert.SerializeObject(Enum.GetValues(typeof(ListOptions)).Cast<int>().Select(e => new { Id = (int)  e, Name = typeof(ListOptions).GetEnumName(e) }));
    JsonString.Dump(); // [{"Id":0,"Name":"Unknown"},{"Id":1,"Name":"Open"},{"Id":2,"Name":"Closed"},{"Id":3,"Name":"Approve"}]
}

public enum ListOptions { 
    Unknown = 0,
    Open = 1,
    Closed = 2,
    Approve = 3 
};
ExternalUse
  • 2,053
  • 2
  • 25
  • 37
  • I'm not really sure I understand your problem. Since you're using [tag:json.net], is it sufficient to use `StringEnumConverter` as shown in [this answer](https://stackoverflow.com/questions/2441290/net-json-serialization-of-enum-as-string/20663621#20663621) to [.NET - JSON serialization of enum as string](https://stackoverflow.com/q/2441290)? If not, can you include a [mcve] showing the data model you want to serialize and the desired JSON? – dbc Jan 13 '19 at 02:31
  • Hi @dbc, I had hoped I did; `StringEnumConverter` will only convert one entry, not the whole enumeration. I'll revisit my question and try to improve it. – ExternalUse Jan 13 '19 at 10:31

2 Answers2

2

You may have static method like

public static EnumToDictionary<string, string> EnumToDictionary<T>() where T: Enum
{
    var res = Enum.GetValues(typeof(T)).Cast<T>()
        .ToDictionary(e => Convert.ToInt32(e).ToString(), e => e.ToString());

    return res;
}

then for Serializing as object

var enumValues=  EnumToDictionary<ListOptions>();
var result = JsonConvert.SerializeObject(enumValues);

for serializing as array

var enumValues=  EnumToDictionary<ListOptions>().ToArray();
var result = JsonConvert.SerializeObject(enumValues);
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
  • 2
    I shall try this out asap, then accept or comment again. Will need a moment to compare and analyze. Thank you! – ExternalUse Jan 13 '19 at 16:29
  • 1
    `where T: Enum` requires C#7.3; just found that my VS was set to "latest major version" and didn't like that constraint. Also found that I need `using static ....Extensions.Enum.EnumExtensions;` to shorten the call, had to hunt a little bit until I could use the method. I've changed it back to Dictionary but apart from that it appears to work. Thank you! – ExternalUse Jan 13 '19 at 17:11
1

Here is an example from Microsoft Docs that convert Enum to Dictionary

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#enum-constraints

Then you can serialize the dictionary to JSON.

shingo
  • 18,436
  • 5
  • 23
  • 42