用Gson解析嵌套对象

时间:2016-12-08 09:28:55

标签: android gson

我有Json文件:

{
  "persons": [
    {
      "name": "Dan",
      "surename": "Govi",
      "PersonData": {
        "height ": "180",
        "weight": "80"
      }
    },
    {
      "name": "John",
      "surename": "Babu",
      "PersonData": {
        "height ": "160",
        "weight": "75"
      }
    },
    {
      "name": "Ivan",
      "surename": "Slav",
      "PersonData": {
        "height ": "200",
        "weight": "160"
      }
    }
  ]
}

这是我的PersonListHolder类:

public class PersonListHolder {

private List<Persons> personList;

public List<Persons> getPersonList() {
    return personList;

}
}

人类:

public class Persons {


    String name;
    String surename;

    PersonData personData;

    public PersonData getPersonData() {
        return personData;
    }

    public class PersonData{

        String height ;
        String weight;

        public String getHeight() {
            return height;
        }

        public String getWeight() {
            return weight;
        }

        public String getMaxAverageBitrate() {
            return MaxAverageBitrate;
        }
    }

    public String getName() {
        return name;
    }

    public String getSureName() {
        return surename;
    }


}

我如何得到它们:

Gson gson = new Gson();
 gson.fromJson(myJson,PersonListHolder.class);

 PersonListHoldertst tst = gson.fromJson(myJson,PersonListHolder.class);

    Persons cd1 = tst.getPersonList().get(0);
    Log.d("DTAG","D1: "+cd1.getName());

    Persons.PersonData cd2 = cd1.getPersonData();

    Log.d("DTAG","D2: "+cd2.getHeight());

在第一个日志中,我看到了结果,但在第二个日志中,我得到了空白

Attempt to invoke virtual method 'java.lang.String ---- on a null object reference

3 个答案:

答案 0 :(得分:1)

几个错误

public class PersonListHolder {

private List<Persons> persons;

public List<Persons> getPersonList() {

return personList;

 }
}

public class Persons {


String name;
String surename;

@SerializeName("PersonData")
PersonData personData;

public PersonData getPersonData() {
    return personData;
    }

public class PersonData{

    String height ;
    String weight;

    public String getHeight() {
        return height;
    }

    public String getWeight() {
        return weight;
    }

    public String getMaxAverageBitrate() {
        return MaxAverageBitrate;
     }
 }

public String getName() {
    return name;
}

public String getSureName() {
    return surename;
 }
}

答案 1 :(得分:0)

应该是不是personList的人

 public class PersonListHolder {

private List<Persons> persons;

public List<Persons> getPersonList() {
return personList;

 }
}

答案 2 :(得分:0)

进行以下更改....属性名称区分大小写

    @SerializedName("PersonData")
    PersonData personData;