Search code examples
javajsonweb-servicesnested-loops

Building JSON with java overwrites values


I'm trying to represent some info from the database with a json, the json structure is created well but don't know why overwrittes the last record from the database. So on my json I just got the last value readed instead al the values.

To do this I use a ResultSet from the main values and an iteration. Inside this iteration I get the related information, so this data is nested on the json. that's my code:

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();

I checked the debug and I get all the records but on the json response I just get the last one result.


Solution

  • 1.) Initialize your section and question inside loop

    2.) Add section into json inside outter 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
              }