2014-01-08 20 views
1

簡稱:構建JSONArray與一個JSONObjects動態的Android

Input => 1001,1002,1003...n 
Desired output => "recipients":[{"@id":"1001"},{"@id":"1002"},{"@id":"1003"},...n] 

我怎樣才能將輸入轉換成所需的輸出JSONArray。

我開始與

try { 
    JSONArray mainArray = new JSONArray(); 
    JSONObject vm = new JSONObject(); 
    JSONObject content = new JSONObject(); 
    JSONObject content1 = new JSONObject(); 

    vm.put("@id", "10000"); 
    content.put("@id","10001"); 
    content1.put("@id","10002"); 

    mainArray.put(","); 

} catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

,但我不上的光路。任何想法 ?

回答

4

與此代碼嘗試

try { 
    int[] ids = { 100, 200, 300 }; 
    JSONObject mainObject = new JSONObject(); 
    JSONArray recipients = new JSONArray(); 
    for (int id : ids) { 
     JSONObject idsJsonObject = new JSONObject(); 
     idsJsonObject.put("@id", id); 
     recipients.put(idsJsonObject); 
    } 
    mainObject.put("recipients", recipients); 
    System.out.println(mainObject.toString()); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
+0

謝謝你它的工作原理:) – Dimitri