title: Dynamically created JSON Object in Java
body: <p>I'm trying to build a JSON object in my servlet.
  The object should look like this:</p>
  
  <pre><code>{
      "firms": [
      {
          "name": "firm1",
          "projects": [
          {
              "name": "firm1project1"
          },
          {
              "name": "firm1project2"
          },
          {
              "name": "firm1project3"
          }
          ]
      },
      {
          "name": "firm2",
          "projects": [
          {
              "name": "firm2project1"
          },
          {
              "name": "firm2project2"
          },
          {
              "name": "firm2project3"
          }
          ]
      },
      {
          "name": "firm3",
          "projects": [
          {
              "name": "firm3project1"
          },
          {
              "name": "firm3project2"
          },
          {
              "name": "firm3project3"
          }
          ]
      },
      {
          "name": "firm4",
          "projects": [
          {
              "name": "firm4project1"
          },
          {
              "name": "firm4project2"
          },
          {
              "name": "firm4project3"
          }
          ]
      }
      ]
  }
  </code></pre>
  
  <p>I have a problem in creating array of project names objects:</p>
  
  <pre><code>[
       {
           "name": "firm2project1"
       },
       {
           "name": "firm2project2"
       },
       {
           "name": "firm2project3"
       }
  ]
  </code></pre>
  
  <p>Right now I have the code as showed below (oJsonInner is a JSONObject object, aProjects - ArrayList of JSONObject type). I build the oJsonInner object from the results I get from database query:</p>
  
  <pre><code>while(result.next()){
  oJsonInner.put("name",result.getString("project_name"));
  aProjects.add(oJsonInner);
  }
  </code></pre>
  
  <p>Is there any way to get the value of the oJsonInner object in <code>aProjects.add(oJsonInner);</code> so during the next loop I could create a new oJsonInner object with different "project_name" value without updating the object that got into aProjects array during the first loop?  </p>