Deserialize json to c # classes

I am trying to create a UWP application using the RIOT API for League of Legends.

When I go to their site to create JSON, I get something like this:

{"gigaxel": { "id": 36588106, "name": "Gigaxel", "profileIconId": 713, "revisionDate": 1451577643000, "summonerLevel": 30 }} 

When I select this JSON and copy it to a new class using the special paste method in Visual Studio 2015, I get these classes with these properties:

 public class Rootobject { public Gigaxel gigaxel { get; set; } } public class Gigaxel { public int id { get; set; } public string name { get; set; } public int profileIconId { get; set; } public long revisionDate { get; set; } public int summonerLevel { get; set; } } 

I created a new class called LOLFacade to connect to RiotAPI:

  public class LOLFacade { private const string APIKey = "secret :D"; public async static Task<Rootobject> ConnectToRiot(string user,string regionName) { var http = new HttpClient(); string riotURL = String.Format("https://{0}.api.pvp.net/api/lol/{0}/v1.4/summoner/by-name/{1}?api_key={2}",regionName, user, APIKey); var response = await http.GetAsync(riotURL); var result = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<Rootobject>(result); } } 

This is the button event handler method:

  Rootobject root = new Rootobject { gigaxel = new Gigaxel() }; root = await LOLFacade.ConnectToRiot("gigaxel","EUNE"); string name = root.gigaxel.name; int level = root.gigaxel.summonerLevel; InfoTextBlock.Text = name + " is level " + level; 

I hardcoded the domain and user name for testing purposes. This works with my username: "gigaxel".
When I try a different username, for example "xenon94", I get an exception:

 Object reference not set to an instance of an object. 

When I change the property name in Rootobject from gigaxel to xenon94 as follows:

 public class Rootobject { public Gigaxel xenon94 { get; set; } } 

When I recompile my code, it works for the username xenon94 , but it does not work for my username "gigaxel" .
I want it to work for any username.

+8
json c #
source share
1 answer

The problem is that the json object has a property called gigaxel. You will need to restore the internal object, for example:

 var json = JsonConvert.DeserializeObject<JObject>(x).First.First; 

From there, you can get the name and other things using the indexer:

 string name = (string)json["name"]; int summonerlevel = (int)json["summonerLevel"] 

To develop, JsonConvert.DeserializeObject (x) will return a new JObject that has only one object. Therefore, the first challenge. Moreover, this object has only one property, called a gigaxel. The value of this property is the required information, for example. name. We want to get this information regardless of the name of the property. Therefore, we first call First to get the value of this property.

+7
source share

All Articles