user3728897
user3728897

Reputation: 13

parsing JSONObject to custom class

my data from my custom class isn't showing.

I get my JSON object from php script and I store it in String result, then I try to insert it to my custom class Planets from that class I call specific variable by get Method but it doesn't show in my TextView result_tv

here is code:

String jsonString = result;
Gson gson = new Gson();
Planets seznamPlanet = gson.fromJson(jsonString, Planets.class);
this.result_tv.setText(seznamPlanet.getPlanetName());
//this.result_tv.setText(jsonString); this works

my class is:

public class Planets {
    public String name;
    public Integer size;
    public Integer o2;
    public Integer atmosphere;

    public String getPlanetName() {
        return name;
    }

    public Integer getPlanetSize() {
        return size;
    }

    public Integer getPlanetO2() {
        return o2;
    }

    public Integer getPlanetAtmosphere() {
        return atmosphere;
    }
}

and JSON object inside result string looks like this:

    {"Planets":[{"name":"Earth","size":"3","o2":"1","atmosphere":"1"},{"name":"Mars","size":"8","o2":"0","atmosphere":"0"}]}

Upvotes: 1

Views: 1516

Answers (2)

Martin Konecny
Martin Konecny

Reputation: 59681

Rename your Planets class to Planet (to avoid conflict)

public class Planet {
  public String name;
  public Integer size;
  public Integer o2;
  public Integer atmosphere;
}

Create another class named PlanetsList

public class PlanetsList {
    List<Planet> Planets; //rename was useful so we don't have List<Planets> Planets
}

Then call gson like so:

PlanetsList seznamPlanet = gson.fromJson(jsonString, PlanetsList.class);

Upvotes: 1

Helix
Helix

Reputation: 1310

Try something like this :

 public class Planets {
    public Planet[] planets;

    @Override
    public String toString() {
        return (new Gson().toJson(this));
    }

    public final class Planet {
        public String name;
        public Integer size;
        public Integer o2;
        public Integer atmosphere;

        @Override
        public String toString() {
            return (new Gson().toJson(this));
        }
    }
}

Upvotes: 0

Related Questions