Talen Kylon Talen Kylon - 3 years ago 209
JSON Question

Parsing a string to a generic Enum type

I'm trying to take some json input and parse into the correct enum type. I have 3 Enum types:

public class Enums
{
public enum Motivators{
Small_Motivator,
Medium_Motivator,
Large_Motivator
}

public enum Reactors{
Small_Reactor,
Large_Reactor
}

public enum Movers{
Small_Mover,
Large_Mover
}
}


I have a method that takes a generic Enum type, and parses to check which type we have.

private void InitializeGenerator(Enum enumType)
{
if (enumType is Enums.Motivators)
{
// work work work work work
}
else if (enumType is Enums.Reactors)
{
// work
}
else if (enumType is Enums.Movers)
{
// work
}
else
{
// we dont know what it is
}
}


My json would look something like this..

{
"WorkerType":"Small_Motivator"
}


And then trying to parse the json..

JObject jObject = JObject.Parse(json);
JToken worker = jObject.GetValue("WorkerType");
Enum workerType = (Enum)Enum.Parse((typeof(Enum)), worker.ToString(), true);
InitializeGenerator(workerType);


throws the following error:

An exception of type 'System.ArgumentException' occurred in mscorlib.dll but was not handled in user code

Additional information: Type provided must be an Enum.

Answer Source

You can easy parse string to your enum instance. But you should define enum types

static void Main(string[] args)
{
    string worker = "Small_Motivator";

    var provider = new EnumProvider();

    var enumValue = provider.GetByValue(worker);
}

public class EnumProvider
{
    public object GetByValue(string sourceStr)
    {
        var enumTypes = new[]
        {
            typeof(Enums.Motivators),
            typeof(Enums.Movers),
            typeof(Enums.Reactors)
        };

        foreach (var type in enumTypes)
        {
            var enumValues = Enum.GetValues(type)
                .Cast<object>()
                .Select(x => x.ToString())
                .ToArray();

            if (enumValues.Any(x => x == sourceStr))
            {
                return Enum.Parse(type, sourceStr);
            }
        }

        throw new ArgumentException($"{sourceStr} not supported");
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download