[英]How to proceed rest response to JSON
我執行異步請求( REST query
)。 從服務器端獲取響應是...
[{"id":2,"name":"Flowers"},{"id":3,"name":"Trees"}]
我需要將響應字符串解析為JSONObject
,然后解析為
ArrayList<Map<String, String>>
在我的下一個獲取數據的async
方法中(注釋了一些代碼):
//async getting data
@Override
public void onSuccessResult(String response) {
String message;
Log.d(Constants.LOG, response);
try {
JSONObject jsonResponse = new JSONObject(response);
/*
JSONArray jsonArray = jsonResponse.getJSONArray("id");
data.clear();
for(int i=0;i<jsonArray.length()-1;i++){
HashMap<String, String> m = new HashMap<String, String>();
JSONArray url = jsonArray.getJSONArray(i);
m.put("name", url.getString(0));
dataPlants.add(m);
//sAdapter.notifyDataSetChanged();
*/
}catch (JSONException e) {
Log.d(Constants.LOG, e.toString());
e.printStackTrace();
}
我得到下一個exception
:
org.json.JSONException: Value
[{"id":2,"name":"Flowers"},{"id":3,"name":"Trees"}] of type org.json.JSONArray cannot be converted to JSONObject
因此,如何適當地進行response
問題來自以下事實:您正在嘗試從表示JSONArray的字符串創建JSONObject
您需要將String解析為JSONArray。
JSONObject jsonResponse = new JSONObject(response);
應該
JSONArray jsonResponse = new JSONArray(response);
在
jsonResponse = new JSONArray(response);
//data.clear();
for (int i = 0; i < jsonResponse.length(); i++) {
Object obj = jsonResponse.get(i);
if(obj instanceof JSONObject) {
HashMap<String, String> m = new HashMap<>();
JSONObject object = jsonResponse.getJSONObject(i);
m.put(object.getString("id"), object.getString("name"));
dataPlants.add(m);
}
}
//sAdapter.notifyDataSetChanged();
@ Edit: 另外,我編輯了代碼,因此在那里有一個對象驗證。
老實說,每當處理JSON文件時, 都應將它們視為對象,並檢查它們是JSONObject實例還是JSONArray實例,因為兩者都有不同的解析機制
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.