我有点问题 我编写了一个从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"}]}
我的问题是:如果我想使用for循环创建另一个名为innerObject3,innerObject4,innerObject5 ....等的JSONObject,该怎么办? 有什么建议?
答案 0 :(得分: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();
希望这可以帮助别人:)