Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法以此格式构造JSON响应_Java_Json - Fatal编程技术网

Java 无法以此格式构造JSON响应

Java 无法以此格式构造JSON响应,java,json,Java,Json,我需要以这种格式构造JSON响应 { label : "name", items : [ {name : "Name1"}, {name : "Name2"} ] } 在我的Servlet程序中,我是这样使用的 List list = new ArrayList(); for (int i = 0; i <= 10; i++) { list.add("Test"); }

我需要以这种格式构造JSON响应

{
   label : "name",
   items : [
       {name : "Name1"},
       {name : "Name2"}
   ]
}
在我的Servlet程序中,我是这样使用的

List list = new ArrayList();

        for (int i = 0; i <= 10; i++) {
            list.add("Test");
        }

        JSONObject json = new JSONObject();
        json.put("label", "name");
        json.put("items", list.toArray());

        response.getWriter().write(json.toString());

请告诉我如何以这种格式构造

必须在阵列内创建对象。这应该起作用:

List list = new ArrayList();

for (int i = 0; i <= 10; i++) {
    JSONObject nextObject = new JSONObject();
    nextObject.put("name", "Name" + i);
    list.add(nextObject);
}

JSONObject json = new JSONObject();
json.put("label", "name");
json.put("items", list.toArray());

response.getWriter().write(json.toString());
List List=new ArrayList();

对于(int i=0;i您必须在数组中创建对象。这应该可以:

List list = new ArrayList();

for (int i = 0; i <= 10; i++) {
    JSONObject nextObject = new JSONObject();
    nextObject.put("name", "Name" + i);
    list.add(nextObject);
}

JSONObject json = new JSONObject();
json.put("label", "name");
json.put("items", list.toArray());

response.getWriter().write(json.toString());
List List=new ArrayList();

对于(inti=0;i我想说的一件事是,在您想要的json数据中,有一个数据结构,我们需要将json对象放入列表,然后将列表放入json对象引用。

我想说的一件事是,在您想要的json数据中,有一个数据结构,我们需要将json对象放在列表中,然后将列表放在json对象引用中。