繁体   English   中英

如何创建动态JSONObject?

[英]How to create a dynamic 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"}]}

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

感谢您的回复,我已设法解决此问题,如下所示:

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();

希望这可以帮助其他人:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM