这个问题似乎离题了,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或include a minimal example在问题本身。
关闭 8 年前。
我想使用 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",
"type": "STRING"
},
{
"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 中将 'put' 方法替换为 'element',在 JSONArray 中将 'put' 方法替换为 'add'。
https://stackoverflow.com/questions/22042638/