以下是初始化的正确方法JSONArray
public class TestJSON {
public static void main(String[] args) {
JSONArray template = new JSONArray("[ {\"name\": \"red\", \"first\": true, \"url\": \"#Red\"}," +
" {\"name\": \"green\", \"link\": true, \"url\": \"#Green\"}," +
"{\"name\": \"blue\", \"link\": true, \"url\": \"#Blue\"} ]");
System.out.println(template.toString());
}
}
以下是输出:
[
{
"name": "red",
"first": true,
"url": "#Red"
},
{
"link": true,
"name": "green",
"url": "#Green"
},
{
"link": true,
"name": "blue",
"url": "#Blue"
}
]
编辑1:
您可以使用以下代码创建完整的 JSON 对象。
public static void main(String[] args) {
JSONArray template = new JSONArray(
"[ {\"name\": \"red\", \"first\": true, \"url\": \"#Red\"},"
+ " {\"name\": \"green\", \"link\": true, \"url\": \"#Green\"},"
+ "{\"name\": \"blue\", \"link\": true, \"url\": \"#Blue\"} ]");
JSONObject object = new JSONObject();
object.put("header", "Colors");
object.put("empty", false);
object.put("items", template);
System.out.println(object.toString());
}
以下是输出:
{
"items": [
{
"name": "red",
"first": true,
"url": "#Red"
},
{
"link": true,
"name": "green",
"url": "#Green"
},
{
"link": true,
"name": "blue",
"url": "#Blue"
}
],
"empty": false,
"header": "Colors"
}
编辑2:
以下代码可用于生成完整的 JSON 对象,而无需使用包含 JSON 数据的字符串:
public static void main(String[] args) {
JSONArray template = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("name", "red");
obj.put("first", true);
obj.put("url", "#Red");
template.put(obj);
JSONObject obj1 = new JSONObject();
obj1.put("name", "green");
obj1.put("link", true);
obj1.put("url", "#Green");
template.put(obj1);
JSONObject obj2 = new JSONObject();
obj2.put("name", "blue");
obj2.put("link", true);
obj2.put("url", "#Blue");
template.put(obj2);
JSONObject object = new JSONObject();
object.put("header", "Colors");
object.put("empty", false);
object.put("items", template);
System.out.println(object.toString());
}
以下是该程序的输出:
{
"items": [
{
"name": "red",
"first": true,
"url": "#Red"
},
{
"link": true,
"name": "green",
"url": "#Green"
},
{
"link": true,
"name": "blue",
"url": "#Blue"
}
],
"empty": false,
"header": "Colors"
}