title: How to create a JSON file in a particular format in Java
body: <p>I am trying to write a JSON file using Java in a particular format. For example: let's suppose I like to get the JSON file written in the following format: </p>
  
  <pre><code>{
  "resource":[{"name":"Node1"}],
  
  "literals":[{"literal":"A", "B", "C", "D"}]
  }
  </code></pre>
  
  <p>As you may notice, in <code>resource</code>, I would like to write strings in there and in <code>literals</code>, I like to have an arraylist of strings. Here are my Java codes:</p>
  
  <pre><code>public void writeJSON() {
  
  public ArrayList&lt;String&gt; literals  = new ArrayList&lt;String&gt;();  
  
  literals.add("A");
  literals.add("B");
  literals.add("C");
  literals.add("D");
  
  JSONObject jsonObject = new JSONObject();
  JSONArray jsonArray = new JSONArray();
  
  jsonObject.put("name", resources.getResource());
  
  resources.setLiterals(literals);
  
  jsonObject.put("literal", resources.getLiterals());
  
  try {
  
      FileWriter file = new FileWriter("/Users/Documents/sample.json");
      file.write(jsonObject.toJSONString());
      file.flush();
      file.close();
  
          } catch (IOException e) {
            e.printStackTrace();
          }
  }
  </code></pre>
  
  <p>Here is the Java file where I set and get values for the JSON file:</p>
  
  <pre><code>public class Resources {
  
  String resource;
  ArrayList&lt;String&gt; literals;
  public Resources()
  {
  
  }
  public void setResource(String resource) 
  {  
          this.resource = resource;
  }  
  
  public String getResource()
  {
      return resource;
  }
  public void setLiterals(ArrayList&lt;String&gt; literals) 
  {  
    this.literals = literals;  
  }
  public ArrayList&lt;String&gt; getLiterals() 
  {  
        return literals;  
  }  
  }
  </code></pre>
  
  <p>Could anyone please help me how to create a JSON file based on the format provided above. Your help would be very much appreciated. </p>