鏈接: - http://api.androidhive.info/contacts/ 問題: - 從給定鏈接我能夠解析聯繫人屬性值,但無法解析電話屬性值。 代碼: -如何從給定鏈接使用Gson解析json數據
class GetGSONdata extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://api.androidhive.info/contacts/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int responsecode = urlConnection.getResponseCode();
Log.e("responsecode", responsecode + "");
InputStreamReader inputStreamReader = new InputStreamReader(urlConnection.getInputStream(), "UTF-8");
Gson gson = new Gson();
JsonReader reader = new JsonReader(inputStreamReader);
reader.beginObject();
while (reader.hasNext()) {
String aname = reader.nextName();
Log.e("Array name", aname);
if (aname.equalsIgnoreCase("contacts")) {
reader.beginArray();
while (reader.hasNext()) {
Contacts contacts = gson.fromJson(reader, Contacts.class);
list.add(contacts);
}
}
}
reader.endObject();
reader.close();
} catch (Exception e) {
Log.e("Exception test", e.toString());
}
for (int i = 0; i < list.size(); i++) {
Log.e("json data", list.get(i).getId() + " " + list.get(i).getName());
}
return null;
}
}
public class Contacts {
private String id;
private String name;
private String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
class Phone{
private String mobile;
private String home;
private String office;
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getHome() {
return home;
}
public void setHome(String home) {
this.home = home;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
}
}
謝謝。
能否請您發表您的'Contacts'類面臨的任何問題? –
@PauloAvelar是的,我已更新代碼。謝謝 –
保留電話類作爲一個單獨的類,並在您的聯繫人類中爲手機添加getter方法,因爲手機是聯繫人對象內的單獨對象。所以,getPhone將完全返回給你電話對象。希望這會有所幫助 – Santhana