APL
APL

Reputation: 355

How to use string to enum converter for JSON deserialize?

I have this JSON string:

string json=@"['Apple','Mango','Orange']";

I have the following enum:

public enum Fruits
{
    Apple=1,
    Mango=2,
    Orange=3
}

I want to deserialize it such that it gives the corresponding array of enums.

int[] result= JsonConvert.Derserialize<int[]>(json)// I want results as [1,2,3]

Upvotes: 2

Views: 1049

Answers (1)

Sudarson Soundararajan
Sudarson Soundararajan

Reputation: 247

You can use the below code to do the same.

class Program
{
    static void Main(string[] args)
    {
        string json = @"['Apple','Mango','Orange']";

        string[] jsonNew = JsonConvert.DeserializeObject<string[]>(json);            

        int[] jsonIntNew = jsonNew.AsEnumerable()
                                  .Select(p => (int)Enum.Parse(typeof(Fruits), p, true))
                                  .ToArray();

        Console.Read();

    }
}

public enum Fruits
{
    Apple = 1,
    Mango = 2,
    Orange = 3
}

You can go with the below code to handle it in a single line

static void Main(string[] args)
{
    string json = @"['Apple','Mango','Orange']";

    //string[] jsonNew = JsonConvert.DeserializeObject<string[]>(json);            

    int[] jsonIntNew = JsonConvert.DeserializeObject<string[]>(json).AsEnumerable()
                       .Select(p => (int)Enum.Parse(typeof(Fruits), p, true)).ToArray();

    Console.Read();

}

Upvotes: 3

Related Questions