Reputation:
I have these classes:
class Game
{
public List<Participant> Participants = new List<Participant>();
}
class Participant
{
public int ChampionId { get; set; }
public string SummonerName { get; set; }
public int SummonerId { get; set; }
}
public class APICalls
{
//private Game game;
private string GetResponse(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
public void GetParticipants()
{
// create a string from the JSON output
var jsonString = GetResponse("https://euw1.api.riotgames.com/lol/league/v3/positions/by-summoner/27528610?api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// fill the Participants list from the Game class with participants based on the contents of the jsonString variable
Game.Participants = JsonConvert.DeserializeObject<Game>(jsonString);
}
}
I want to fill my Participants list in the Game class with the GetParticipants method in the APICalls class. My problem is that I can't access the list from this class.
I would like to keep all my API code in one class file which is why I made this class.
What am I doing wrong?
Upvotes: 0
Views: 1839
Reputation: 61784
Participants is not a static property. You need to declare an instance of the class. You also appear to be trying to desieralise the JSON into a "Game" object, but then assign it to the Participants property. I've assumed that actually the JSON is returning a list of participants and amended accordingly, but that may not be the case.
Game game = new Game();
game.Participants = JsonConvert.DeserializeObject<List<Participant>>(jsonString);
Upvotes: 0
Reputation: 2945
Either create an object of Game
and refer to Participants
using game.Participants
as shown below:
Game game = new Game();
game.Participants = JsonConvert.DeserializeObject<Game>(jsonString);
Or
Make the Participants list static:
class Game
{
public static List<Participant> Participants = new List<Participant>();
}
And access the Participants
list it directly then using Game.Participants
Upvotes: 1
Reputation: 460028
You need an instance of the Game
class in order to use it's (non static) fields:
var game = new Game();
game.Participants = JsonConvert.DeserializeObject<Game>(jsonString);
If you only want one instance you could make the field static
, then your code works. But note that you might get problems if multiple threads access that list at the same time then.
Upvotes: 2