我想使用
JSONObject和
JSONArray来构建一个类似于使用java结构的JSON对象.
我已经经历了堆栈溢出的各种职位,这表明使用我无法识别JSONArray的push,put等方法.请帮忙.
{ "name": "sample","def": [ { "setId": 1,"setDef": [ { "name": "ABC","type": "STRING" },{ "name": "XYZ","type": "STRING" } ] },{ "setId": 2,"setDef": [ { "name": "abc",{ "name": "xyz","type": "STRING" } ] } ] }
使用导入org.json.JSONArray和org.json.JSONObject
原文链接:https://www.f2er.com/json/288510.htmlJSONObject object = new JSONObject(); object.put("name","sample"); JSONArray array = new JSONArray(); JSONObject arrayElementOne = new JSONObject(); arrayElementOne.put("setId",1); JSONArray arrayElementOneArray = new JSONArray(); JSONObject arrayElementOneArrayElementOne = new JSONObject(); arrayElementOneArrayElementOne.put("name","ABC"); arrayElementOneArrayElementOne.put("type","STRING"); JSONObject arrayElementOneArrayElementTwo = new JSONObject(); arrayElementOneArrayElementTwo.put("name","XYZ"); arrayElementOneArrayElementTwo.put("type","STRING"); arrayElementOneArray.put(arrayElementOneArrayElementOne); arrayElementOneArray.put(arrayElementOneArrayElementTwo); arrayElementOne.put("setDef",arrayElementOneArray); array.put(arrayElementOne); object.put("def",array);
为了清楚起见,我没有包括第一个数组的第二个元素.希望你得到点.
编辑:
以前的答案是假设你使用的是org.json.JSONObject和org.json.JSONArray.
对于net.sf.json.JSONObject和net.sf.json.JSONArray:
JSONObject object = new JSONObject(); object.element("name","sample"); JSONArray array = new JSONArray(); JSONObject arrayElementOne = new JSONObject(); arrayElementOne.element("setId",1); JSONArray arrayElementOneArray = new JSONArray(); JSONObject arrayElementOneArrayElementOne = new JSONObject(); arrayElementOneArrayElementOne.element("name","ABC"); arrayElementOneArrayElementOne.element("type","STRING"); JSONObject arrayElementOneArrayElementTwo = new JSONObject(); arrayElementOneArrayElementTwo.element("name","XYZ"); arrayElementOneArrayElementTwo.element("type","STRING"); arrayElementOneArray.add(arrayElementOneArrayElementOne); arrayElementOneArray.add(arrayElementOneArrayElementTwo); arrayElementOne.element("setDef",arrayElementOneArray); object.element("def",array);
基本上是相同的,在JSONObject中替换’element’的方法’put’,在JSONArray中替换’add’.