我正在尝试使用AsyncTask从json数据中获取值。我只得到了最后一个价值而且我不明白为什么......
我试着为每个人解析,但我做错了什么:
这是我的代码:
private class DecodeData extends AsyncTask<String, Void, String> {
protected ArrayList<HashMap<String, String>> decodedArray;
protected HashMap<String, String> decodedMap;
protected Iterator<String> it;
protected JSONArray m_Array;
protected JSONObject object;
protected String response;
protected String keys;
protected String value;
@SuppressWarnings("unchecked")
@Override
protected String doInBackground(String... params) {
response = params[0];
keys = "";
value = "";
object = null;
decodedArray = new ArrayList<HashMap<String, String>>();
try {
JSONArray arrayResp = new JSONArray(response);
for (int i = 0; i < arrayResp.length(); i++) {
decodedMap = new HashMap<String, String>();
it = arrayResp.getJSONObject(i).keys();
while (it.hasNext()) {
keys = (String)it.next();
value = Base64.DecodeStrToStr((String)arrayResp.getJSONObject(i).get(keys));
decodedMap.put("\""+keys+"\"", "\""+value+"\"");
object = new JSONObject(decodedMap.toString());
Log.i("DECODED MAP : ", object.toString());
m_Array = new JSONArray();
m_Array.put(object);
Log.i("M_ARRAY", ""+m_Array);
}
// decodedArray.add(decodedMap);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// array = new JSONArray(decodedArray);
return m_Array.toString();
}
我正在使用Volley来获得回应。之后,我使用此响应创建一个JSONArray,并从中获取所有键/值。我将所有这些都放在我的Hashmap中。但是当我在这里放置键/值:m_Array.put(object)时,它只放入我的json数据的最后一个值。任何人都知道我做错了什么?
答案 0 :(得分:6)
请在开始循环之前创建JSONArray ..
m_Array = new JSONArray();
JSONArray arrayResp = new JSONArray(response);
for (int i = 0; i < arrayResp.length(); i++) { ....