Using Gson to convert Json into Java Object -
i working on project using steam web api. api returns data in json format , wanted make java program uses data. here following json format api:
{ "response": { "players": [ { "steamid": "---", "communityvisibilitystate": 1, "profilestate": 1, "personaname": "---", "lastlogoff": 1429915502, "profileurl": "---", "avatar": "---", "avatarmedium": "---", "avatarfull": "---", "personastate": 0 } ] } }
i using google's json api called gson , having trouble setting java classes can use fromjson()
method.
from json data, know there array of players
objects contain data. 1 thing confusing me outer tag called response
. know have construct class representing players
objects have create class represents response
since encloses players
?
as of right now, have file named response.java
contains 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 , setters omitted. @override public string tostring() { return "<<" + "steamid=" + steamid + "\n" + "name=" + personaname + "\n" + ">>"; } }
i included variables plan use. json data above contained in string called jsondata
, testing in main method:
response response = gson.fromjson(jsondata, response.class); system.out.println(response.getplayerat(0));
however, running gives me indexoutofboundsexception. seems if gson unable information , store object? shed light on problem having? curious know if have set classes correctly.
replace
private arraylist<player> playersummaries = new arraylist<player>();
with
private arraylist<player> players = new arraylist<player>();
gson uses reflection field should populate. in case looking whether have field named players
not.
you not need instantiate field, gson you.
edit:
you need wrapper class around top-level object. so
class myobject { public response response; } myobject myobject = gson.fromjson(jsondata, myobject.class);
Comments
Post a Comment