JsonData to Enum

Hi Unity commmunity, I have an issue.

I’m using LitJson to make a database of items:
78688-7eddcec13596ffe5d07be64192bf3aed.png

I have a class to create a new item, which has the following parameters:

My issue is that when I try to choose the rarity of the item, which is an enum that cosists of {common, uncommon, rare, legendary, …}, I get the following problem:

How do I convert JsonData to an enum?

Well, you need to parse the string you get from your Json data into the appropriate enum value by using System.Enum.Parse:

(Rarity)System.Enum.Parse(typeof(Rarity), itemData*["rarity"])*

instead of
itemData*[“rarity”]*
edit
unfortunately you can’t add extension methods to “types” only to “instances”. You could add this class to your project:
public static class EnumExtension
{
public static T Parse(this System.Enum aEnum, string aText)
{
return (T)System.Enum.Parse(typeof(T), aText);
}
}
It will add the Parse method to each enum value. So you could simply do:
Rarity.common.Parse(itemData*[“rarity”])*
It doesn’t matter which enum member you use. Of course instead of an extension method you could simply place the method in a helper class:
public static class Helper
{
public static T ParseEnum(string aText)
{
return (T)System.Enum.Parse(typeof(T), aText);
}
}
This can be used like this:
Helper.ParseEnum(itemData*[“rarity”])*

Bunny’s answer is very good.
here’s the variant i use:

  public static bool ParseStringToEnum<T>(string s, out T enumValue) where T: struct, IComparable, IFormattable, IConvertible {
    foreach (T enumCandidate in System.Enum.GetValues(typeof(T))) {
      if (s == enumCandidate.ToString()) {
        enumValue = enumCandidate;
        return true;
      }
    }
    
    enumValue = default(T);
    
    return false;
  }

less performant, but won’t throw exception.
hm, maybe one could just put a try/catch around System.Enum.Parse().