I am currently working on a project where I am using the Steam Web API. The API returns data in JSON format and I wanted to make a Java program that uses this data. Here is the following JSON format from the API:
{
"response": {
"players": [
{
"steamid": "---",
"communityvisibilitystate": 1,
"profilestate": 1,
"personaname": "---",
"lastlogoff": 1429915502,
"profileurl": "---",
"avatar": "---",
"avatarmedium": "---",
"avatarfull": "---",
"personastate": 0
}
]
}
}
I am using Google's JSON API called Gson and I am having trouble setting up the Java classes so that I can use the fromJson()
method.
From the JSON data, I know that there is an array of players
objects that contain all the data. The one thing that is confusing me is the outer tag called response
. I know that I have to construct a class representing the players
objects but do I also have to create a class that represents response
since it encloses players
?
As of right now, I have a file named Response.java
that contains the following:
public class Response {
private ArrayList<Player> playerSummaries = new ArrayList<Player>();
public String toString() {
return playerSummaries.get(0).toString();
}
}
class Player {
private String steamid;
private String personaname;
public String getSteamID() {
return steamid;
}
public void setSteamID(String newSteamID) {
steamid = newSteamID;
}
public String getPersonaName() {
return personaname;
}
public void setPersonaName(String name) {
personaname = name;
}
//Rest of getters and setters omitted.
@Override
public String toString() {
return "<<" + "steamid=" + steamid + "\n" + "name=" + personaname + "\n" + ">>";
}
}
I only included the variables that I plan to use. The JSON data above is contained in a String called jsonData
and this is what I am testing in my main method:
Response response = gson.fromJson(jsonData, Response.class);
System.out.println(response.getPlayerAt(0));
However, running this gives me an IndexOutOfBoundsException. It seems as if Gson was unable to get the information and store it into an object? Could anyone shed some light on this problem I am having? I am mostly curious to know if I have set up my classes correctly.