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;
}
}
}
Your JSON contains a single object, not an array.
Therefore, you can only deserialize it as KeyValue
.
Your RevisionDate
property has to be long
, because 1387913628000
, and that's the value your trying to deserialize, exceeds int
range.
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);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With