2017-04-26 35 views
0

我有這樣的代碼JSON對象只保留最後一個記錄

JSONObject output = new JSONObject(); 
JSONObject elements = new JSONObject(); 
JSONArray jsonArrayOutput = new JSONArray(); 
ArrayList<String> name = ArrayList<String>(); 

for (int i=0 ; i<name.size() ; i++){ 

    elements.put("Name", name.get(i)); 
    jsonArrrayOutput.put(elements); 
} 


output.put("Results", jsonArrrayOutput).toString(); 

的問題是,所得到的輸出JSON有隻「名」的ArrayList很多次,不是所有元素的最後一個元素。 我該如何解決它?

回答

0

您正在爲jsonArrayOutput 再次添加元素相同的名稱密鑰嘗試爲每個迭代創建一個新的JSONObject。 例如: -

JSONObject output = new JSONObject(); 
JSONObject elements = new JSONObject(); 
JSONArray jsonArrayOutput = new JSONArray(); 
ArrayList<String> name = ArrayList<String>(); 

for (int i=0 ; i<name.size() ; i++){ 

    JSONObject temp = new JSONObject(); 
    temp.put("Name", name.get(i)); 
    jsonArrrayOutput.put(temp); 
} 


output.put("Results", jsonArrrayOutput).toString(); 
+0

非常感謝。這是解決方案。 –

+0

@ A.Sim接受答案.. – TKHN

0

這裏是我的版本的代碼。您的代碼的問題是您的elements對象的聲明。無論何時您更改elements會改變您添加到陣列中的elementelement

這是因爲當你把element對象到jsonArrayOutput

JSONObject output = new JSONObject(); 
JSONArray jsonArrayOutput = new JSONArray(); 
ArrayList<String> name = new ArrayList<>(); 

for (int i = 0; i < name.size(); i++) { 
    JSONObject elements = new JSONObject(); 
    try { 
      elements.put("Name", name.get(i)); 
      jsonArrayOutput.put(elements); 
    } catch (JSONException e) { 
      e.printStackTrace(); 
    } 
} 

try { 
    output.put("Results", jsonArrayOutput).toString(); 
    Log.i("info",output.toString()); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

希望幫助參考使用!

+0

謝謝。問題已修復。 –

相關問題