2014-04-21 87 views
1

我嘗試將JSONObject值放在「for」指令的JSONArray上,並且第一個值組工作正常,但是當我添加第二個值組時,我發現第一個值也被覆蓋。我把代碼和一個examepl解釋得更好。JSONObject覆蓋JSONArray

JSONArray jsPoints = new JSONArray(); 
JSONObject js = new JSONObject(); 
for(int i = 0; i < points.length; i++) 
{        
    try 
    { 
     js.put("id",points[i]._id); 
     js.put("calification",points[i]._calification); 
     js.put("comment",points[i]._comment); 
     js.put("gps",points[i]._coords); 
     js.put("X",points[i]._X); 
     js.put("Y",points[i]._Y); 
    } 
    catch (JSONException e) 
    {        
     e.printStackTrace(); 
    } 
    jsPoints.put(js); 
} 

我有,例如,該值gruops:

在I = 0:

ID:1 - calification:0 - 評論: 「喜」 - 全球定位系統:0 - X: 220 - Y:110

在i = 1;

ID:2 - calification:2 - 評論: 「你好」 - 全球定位系統:40.324 - X:10 - Y:52

當我把第一值(I = 0),I上jsPoints加入正確,但是當我把第二個值(i = 1)的第一個值被第二個值覆蓋時,我該如何解決這個問題?謝謝!

回答

3
JSONArray jsPoints = new JSONArray(); 

for(int i = 0; i < points.length; i++) 
{  
JSONObject js = null; 

try 
{ 
    js = new JSONObject(); 
    js.put("id",points[i]._id); 
    js.put("calification",points[i]._calification); 
    js.put("comment",points[i]._comment); 
    js.put("gps",points[i]._coords); 
    js.put("X",points[i]._X); 
    js.put("Y",points[i]._Y); 
} 
catch (JSONException e) 
{        
    e.printStackTrace(); 
} 
    if(js!=null) 
    jsPoints.put(js); 

}

+0

accumulate方法對我的追蹤有一個問題,當我使用它時,我收到的值如下所示:[ { 「ID」:[ 「3;」, 「3;」], 「GPS」:[ 「;」, 「;」], 「calification」:[ 「0;」, 「1」;], 「Y」 :[66,43], 「註釋」:[ 「;」, 「FFFF;」], 「X」:[17,31]},{ 「ID」:[ 「3;」, 「3;」], 「GPS」:[ 「;」, 「;」], 「calification」:[ 「0;」, 「1」;], 「Y」:[66,43], 「註釋」:[ 「;」,」 FFFF; 「],」 X「:[17,31]}]。我的意思是,這是重複的,我不想這樣,我想有這樣的事情:[{「id」:[「3;」],「gps」:[「;」],「calification」:[ 「0;」], 「Y」:[66], 「註釋」:[ 「;」], 「X」:[17]},{ 「ID」:[ 「3;」], 「GPS」:[ 「;」],「calification」:[「1;」],「Y」:[43],「comment」:[「ffff;」],「X」:[31]}] – Imrik

+0

我編輯我的答案。請檢查這一點,你應該只刷新你的舊json對象。無需積累:) –

+0

它的工作原理!謝謝! – Imrik

0
try 
{ 
JSONObject js = new JSONObject(); 

JSONArray jsPoints = new JSONArray(); 

for(int i = 0; i < jsPoints.length; i++) 
{        

    js.put("id",points[i]._id); 
    js.put("calification",points[i]._calification); 
    js.put("comment",points[i]._comment); 
    js.put("gps",points[i]._coords); 
    js.put("X",points[i]._X); 
    js.put("Y",points[i]._Y); 
} 
catch (JSONException e) 
{        
    e.printStackTrace(); 
} 
jsPoints.put(js); 
} 
+0

這不起作用,你僅僅只改變的JSONObject和JSONArray報關行,它不會解決問題。 – Imrik

+0

你從url/api收到了什麼回覆 – Amardeepvijay

+0

你是什麼意思? logcat的響應? – Imrik