- Home /
JsonData to Enum
Hi Unity commmunity, I have an issue.
I'm using LitJson to make a database of items:
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: https://gyazo.com/921fc188c1f9c83483617cf160d86e9d
How do I convert JsonData to an enum?
Answer by Bunny83 · Sep 21, 2016 at 05:44 PM
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[i]["rarity"])
instead of
itemData[i]["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<T>(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[i]["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<T>(string aText)
{
return (T)System.Enum.Parse(typeof(T), aText);
}
}
This can be used like this:
Helper.ParseEnum<Rarity>(itemData[i]["rarity"])
Answer by elenzil · Sep 23, 2016 at 12:06 AM
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().
Your answer

Follow this Question
Related Questions
(SOLVED) Serializing different JSON objects, contained in an array, in another JSON object. (C#) 2 Answers
How to set KeyCode with Number for load? C# 1 Answer
Get JSON array object string value 2 Answers
Serialization of an Enum Array 3 Answers
JsonConvert.DeserializeObject Not responding when building IOS project. 0 Answers