2015-03-13 85 views
0

我有一个小问题 我已经写创建的JSONObject对象的代码,并添加一些关于它的数据是这样的:如何创建一个动态的JSONObject?

JSONObject outerObject = new JSONObject(); 
JSONArray outerArray = new JSONArray(); 

JSONObject innerObject1 = new JSONObject(); 

innerObject1.put("id", "semantic web"); 
innerObject1.put("url", "www.semanticweb.com"); 
innerObject1.put("definition", "this is the denfition of semantic web"); 
outerArray.put(innerObject1); 

然后我再创建一个名为innerObject2,做这样相同的过程:

JSONObject innerObject2 = new JSONObject(); 

innerObject2.put("id", "ontology"); 
innerObject2.put("url", "www.ontology.com"); 
innerObject2.put("definition", "this is the denfition of ontology"); 
outerArray.put(innerObject2); 

outerObject.put("rows", outerArray); 
return outerObject.toString(); 

结果会有些事情是这样的:

{"rows":[{"definition":"this is the denfition of semantic web","id":"semantic web","url":"www.semanticweb.com"},{"definition":"this is the denfition of ontology","id":"ontology","url":"www.ontology.com"}]} 

我的问题是:如果什么我想创建另一个名为innerObject3,innerObject4,innerObject5 ....使用for循环的JSONObject? 有什么建议吗?

+0

你可以使用'gson'或类似助手库来操纵java对象到json对象。 – alijandro 2015-03-13 08:04:09

回答

0

感谢您的答复 我设法解决这个问题如下:

JSONObject outerObject = new JSONObject(); 
JSONArray outerArray = new JSONArray(); 

JSONObject [] innerObject = new JSONObject[4]; 
for(int i =0; i<3; i++) 
{ 
    innerObject[i]=new JSONObject(); 
    innerObject[i].put("id", "id of "+i); 
    innerObject[i].put("url", "url of "+i); 
    innerObject[i].put("Definition", "Definition of "+i); 
    outerArray.put(innerObject[i]); 
} 
outerObject.put("rows", outerArray); 
return outerObject.toString(); 

希望这可以帮助别人:)