Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

wcf

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;
        }
    }
}
like image 890
JoJo Avatar asked Dec 25 '13 12:12

JoJo


2 Answers

Your JSON contains a single object, not an array.
Therefore, you can only deserialize it as KeyValue.

like image 124
SLaks Avatar answered Oct 24 '22 06:10

SLaks


  1. Your RevisionDate property has to be long, because 1387913628000, and that's the value your trying to deserialize, exceeds int range.

  2. Your JSON contains information about only one KeyValue object, not an array of there, so you have to deserialize it as KeyValue, no KeyValue[]:

    KeyValue item = js.Deserialize<KeyValue>(strJSON);
    
  3. Having KeyValue instance you can use standard property syntax to return ID:

    return item.id;
    

I find this code working:

public class KeyValue
{
    public int id { get; set; }
    public string name { get; set; }
    public int profileIconId { get; set; }
    public int summonerLevel { get; set; }
    public long revisionDate { get; set; }
}
static void Main(string[] args)
{
    var input = @"{""id"":34379899,""name"":""Revelation22"",""profileIconId"":547,""summonerLevel"":30,""revisionDate"":1387913628000}";

    JavaScriptSerializer js = new JavaScriptSerializer();

     var item = js.Deserialize<KeyValue>(input);

     var summonerId = item.id;
}
like image 9
MarcinJuraszek Avatar answered Oct 24 '22 06:10

MarcinJuraszek