你想要的线路
{"1":"{\"id\":\"1\"}"**,**"2":"{\"id\":\"2\"}"**,**"3":"{\"id\":\"3\"}"}
也不合法,我认为您的意思是(至少)是这样的:
{"1":"{\"id\":\"1\"}","2":"{\"id\":\"2\"}","3":"{\"id\":\"3\"}"}
请注意,这不是JSON 数组,它是一个具有分别称为 1 2 和 3 的字符串字段的对象,它们恰好包含 JSON 语法字符串值。虽然不是非法的,但你真的想要那个是非常值得怀疑的
现在,难道你的意思是
{"1":{"id":"1"},"2":{"id":"2"},"3":{"id":"3"}}
仍然是一个对象,但对象字段分别称为 1 2 和 3,其中对象只有一个称为 id 的字段?无论如何(免责声明:我自己不是 org.json 库用户 - 见下文 - 所以不保证代码的准确性:)):
// Create the outer container
JSONObject outer = new JSONObject();
// Create a container for the first contained object
JSONObject inner1 = new JSONObject();
inner1.put("id",1);
// and add that to outer
outer.put("1",inner1);
// Create a container for the second contained object
JSONObject inner2 = new JSONObject();
inner2.put("id",2);
// and add to outer as well
outer.put("2",inner2);
// Create a container for the third contained object
JSONObject inner3 = new JSONObject();
inner3.put("id",3);
// and add that to outer
outer.put("3",inner3);
// at this point
outer.toString()
// should return the JSON String from my last step.
如果您确实希望它是一个数组,则需要将对象放入 JSONArray 中,并将该数组作为命名字段包装在对象中。最终结果或多或少看起来像这样:
{"data": [{"id":"1"},{"id":"2"},{"id":"3"}]}
内部对象的代码与上面相同,但在内部和外部对象之间有一个新层(数组):
JSONArray middle = new JSONArray();
...
middle.add(inner1);
...
middle.add(inner2);
...
middle.add(inner3);
...
outer.put("data",middle);
仍然不确定这是否是您真正想要的,但我认为这是迈向解决方案的第一步。话虽如此,我建议您切换到比您显然正在使用的 json.org 更好的 JSON Java 库。在此处查看有关可用的不同库的一些反馈,对于我的项目,我已经使用Jackson已经有一段时间了,我对此感到非常满意,但是我链接到的 SO question 谈到了其他几个优秀的替代方案。