2016-12-08 145 views
-3

嵌套的對象我有JSON文件:解析與GSON

{ 
    "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 
+0

你需要在你想GSON解析各個領域的'@ Expose'註解。 'personList'應該是'persons' – Blackbelt

回答

0

應該是人不是personList

public class PersonListHolder { 

private List<Persons> persons; 

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

} 
} 
0

以下改制....屬性名稱是區分大小寫

@SerializedName("PersonData") 
    PersonData personData; 
0

一些錯誤

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