2013-04-11 22 views
0

我需要像這樣形成一個JSON對象。在android中創建JSONObjects

{ 
    "GroupID": 24536, 
    "Section": [1,2,3,4,5] 
} 

這是我試過的,但是當我看着我的對象結構時,節數組沒有正確形成。

JSONObject Object = new JSONObject(); 
Object.put("Group", GroupID); 
int[] section = {1,2,3,4,5}; 
Object.put("Section", section); 

回答

1

嘗試:

JSONObject Object = new JSONObject(); 
    Object.put("Group", GroupID); 
    Integer[] section = {1,2,3,4,5}; 
    Object.put("Section", new JSONArray(Arrays.asList(section))); 
1

您需要使用JSONArray插入代表數組的一組值,在這種情況下INT陣列。


String strJson = null; 
try{ 
    int[] section = {1,2,3,4,5}; 

    JSONObject jo = new JSONObject(); 
    jo.put("GroupId", 24536); 
    JSONArray ja = new JSONArray(); 
    for(int i : section) 
     ja.put(i); 
    jo.put("Section", ja); 

    strJson = jo.toString(); 
} 
catch (Exception e) { 
    e.printStackTrace(); 
} 

現在你已經有了JSON字符串內strJson

+0

u能告訴我的是,我想...但它給我帶來了錯誤。 – Kevin

+0

看到我更新的答案,示例代碼 – waqaslam

1

嘗試:

JSONObject Object = new JSONObject(); 
Object.put("Group", GroupID); 
int[] section = {1,2,3,4,5}; 
JSONArray arr = new JSONArray(); 
arr.put(section); 
Object.put("Section", arr); 

或者創建一個集合,並將其設置爲值:

Collection c = Arrays.asList(section); 
Object.put("Section", c); 
+0

謝謝branky ....爲什麼不是我的情況下工作...爲什麼會arraylist工作? – Kevin

+0

它們都不起作用,因爲它仍然是「Section」:[「java.lang.int」] – Kevin