使用JSONObject为Java中的以下结构创建嵌套JSON对象?
发布时间:2020-12-16 19:49:00 所属栏目:百科 来源:网络整理
导读:我想使用 JSONObject和 JSONArray来构建一个类似于使用java结构的JSON对象. 我已经经历了堆栈溢出的各种职位,这表明使用我无法识别JSONArray的push,put等方法.请帮忙. { "name": "sample","def": [ { "setId": 1,"setDef": [ { "name": "ABC","type": "STRIN
我想使用
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
JSONObject 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’. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |