2013-04-11 21 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