1 回答

TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
通過查看您在問題中發(fā)布的示例 JSON 數(shù)據(jù)格式,我認(rèn)為 API 不會(huì)返回 JSONArray,而是返回JSONObject。不管怎樣,我將告訴您如何從已解析的對象(無論是 JSONArray 還是 JSONObject)中獲取所需的數(shù)據(jù)。
您幾乎接近您正在尋找的解決方案。只需將下面的代碼粘貼到onResponse()方法中即可。
@Override
public void onResponse(Call<List<Pandomats>> call, Response<List<Pandomats>> response) {
pandomats.addAll(response.body());
Log.v("ListPandomats", String.valueOf(pandomats.size()));
for (int i = 0; i < pandomats.size(); i++) {
Pandomats p = pandomats.get(i);
Log.v("ListPandomats", p.getModel()); // prints model
Log.v("ListPandomats", String.valueOf(p.getLatitude())); // prints latitude
}
}
像上面一樣,您可以從Pandomats類中獲取任何對象。確保pandomats在聲明時(shí)或在onResponse()方法內(nèi)部使用它之前已初始化 ArrayList。否則你最終會(huì)得到NullPointerException.
并且不要忘記在onFailure()方法內(nèi)部記錄來自 API 的錯(cuò)誤響應(yīng)。這很重要。
@Override
public void onFailure(Call<List<Pandomats>> call, Throwable t) {
Log.e("ListPandomats", "Error" t);
}
正如我之前所說,我認(rèn)為 API 不會(huì)返回 JSONArray,而是重新運(yùn)行 JSONObject。如果它返回 JSONObject,則需要像下面這樣更改代碼。
JSONApi.java
public interface JsonPlaceApi {
@GET("/api/device/get/")
Call<Pandomats> loadList(); // remove List<> from return type
}
MainActivity.java
Service.getInstance()
.getJSONApi()
.loadList()
.enqueue(new Callback<Pandomats>() { /* remove List<> */
@Override
public void onResponse(Call<Pandomats> call, /* remove List<> */ Response<List<Pandomats>> response) {
Pandomats p = response.body();
// without for loop iteration you can get the data
Log.v("ListPandomats", p.getModel()); // prints model
Log.v("ListPandomats", String.valueOf(p.getLatitude())); // prints latitude
}
@Override
public void onFailure(Call<Pandomats> call, Throwable t) { /* remove List<> */
Log.e("ListPandomats", "Error" t);
}
});
我希望現(xiàn)在一切都清楚了。如果您遇到錯(cuò)誤,請先查看錯(cuò)誤日志。如果不明白,請編輯問題并發(fā)布錯(cuò)誤日志。
添加回答
舉報(bào)