我的自定义类中的数据未显示。

我从php脚本中获取了JSON对象,并将其存储在String result中,然后尝试将其插入到自定义类Planets
从该类中,我通过get方法调用了特定变量,但是它没有显示在TextView result_tv

这是代码:

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


我的课是:

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;
    }
}


结果字符串中的JSON对象如下所示:

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

最佳答案

将您的Planets类重命名为Planet(以避免冲突)

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


创建另一个名为PlanetsList的类

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


然后像这样调用gson:

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

09-11 17:14