How to populate a Generic List from a JSON string using C#.NET?

Viewed 2940

I am trying to populate a List in C# but the values are not appearing in the array - though it does not throw an error until I try and set a variable with an array index (because it is out of range of course).

This is the exact return string strJSON I am seeing while debugging.

strJSON "{\"id\":34379899,\"name\":\"Revelation22\",\"profileIconId\":547,\"summonerLevel\":30,\"revisionDate\":1387913628000}"

Why is the List (array) not populating?

This is the code for KeyValue.cs (which to be honest I do not know yet why it needs another class)

namespace LoLSummoner
{
    public class KeyValue
    {
        public int id {get; set;}
        public string name {get; set;}
        public int profileIconId {get; set;}
        public int summonerLevel {get; set;}
        public int revisionDate {get; set;}
    }
}

And this is the code from Summoner.svc.cs

namespace LoLSummoner
{
    public class Summoner : ISummoner
    {

        public int GetSummonerID(string SummonerName)
        {
            int summonerId = 0;

            WebClient client = new WebClient();
            string strJSON = client.DownloadString("http://prod.api.pvp.net/api/lol/na/v1.2/summoner/by-name/" + SummonerName + "?api_key=xxxx");

            JavaScriptSerializer js = new JavaScriptSerializer();

            KeyValue[] arrJSON = js.Deserialize<List<KeyValue>>(strJSON).ToArray();

            summonerId = Convert.ToInt32(arrJSON.GetValue(0));

            return summonerId;
        }
    }
}
5 Answers
Related