使用 java 构建 JSON 会覆盖值

Building JSON with java overwrites values

我试图用 json 表示数据库中的一些信息,json 结构创建得很好,但不知道为什么会覆盖数据库中的最后一条记录。所以在我的 json 上,我只是读取了最后一个值而不是所有值。

为此,我使用了来自主要值和迭代的结果集。在此迭代中,我获得了相关信息,因此此数据嵌套在 json 上。这是我的代码:

JSONObject json = new JSONObject();
          ResultSet sections = null;
          ResultSet questions = null;
          JSONObject section = new JSONObject();
          JSONObject question = new JSONObject();
          Db d = new Db();


          d.makeJDBCConnection();
          sections = d.getSections();
          while(sections.next()){
              section.put("name", sections.getString("sectionName"));
              section.put("id", sections.getInt("id"));
              questions = d.getQuestions(sections.getInt("id"));
              while(questions.next()){
                  // id, statement
                  question.put("id", questions.getInt("id"));
                  question.put("statement", questions.getString("statement"));
                  section.put("questions", question);
              }
          }

          json.append("section", section);

          return Response.status(200).entity(json.toString()).build();

我检查了调试并获得了所有记录,但在 json 响应中我只获得了最后一个结果。

您重复更新同一个 "question" 和 "section" 对象。每次通过 "while(sections.next())" 循环都应该创建一个新的 "section" 对象,对于 "question."

也是一样

1.) 初始化你的 sectionquestion 内部循环

2.) 在 outter 内将 section 添加到 json while loop

JSONObject json = new JSONObject();
          ResultSet sections = null;
          ResultSet questions = null;
          JSONObject section = null;
          JSONObject question = null;
          Db d = new Db();


          d.makeJDBCConnection();
          sections = d.getSections();
          while(sections.next()){

              section = new JSONObject();
              // initialize new one inside every iteration

              section.put("name", sections.getString("sectionName"));
              section.put("id", sections.getInt("id"));
              questions = d.getQuestions(sections.getInt("id"));
              while(questions.next()){
                  // id, statement

                  question = new JSONObject();
                  // initialize new one inside every iteration

              question.put("id", questions.getInt("id"));
                  question.put("statement", questions.getString("statement"));
                  section.put("questions", question);
              }
          json.append("section", section);
          // ^^ add every created record 
          // should be inside the loop
          }