title: Jackson - best way writes a java list to a json array
body: <p>I want to use jackson to convert a ArrayList to a JsonArray. </p>
  
  <p><strong>Event.java</strong> : this is the java bean class with two fields "field1", "field2" mapped as JsonProperty.</p>
  
  <p>My goal is:</p>
  
  <p>Convert</p>
  
  <pre><code>ArrayList&lt;Event&gt; list = new ArrayList&lt;Event&gt;();
      list.add(new Event("a1","a2"));
      list.add(new Event("b1","b2"));
  </code></pre>
  
  <p>To </p>
  
  <pre><code>[
  {"field1":"a1", "field":"a2"},
  {"field1":"b1", "field":"b2"}
  ]
  </code></pre>
  
  <p>The way I can think of is:
  <strong>writeListToJsonArray()</strong>:</p>
  
  <pre><code>public void writeListToJsonArray() throws IOException {  
      ArrayList&lt;Event&gt; list = new ArrayList&lt;Event&gt;();
      list.add(new Event("a1","a2"));
      list.add(new Event("b1","b2"));
  
      OutputStream out = new ByteArrayOutputStream();
  
      JsonFactory jfactory = new JsonFactory();
      JsonGenerator jGenerator = jfactory.createJsonGenerator(out, JsonEncoding.UTF8);
      ObjectMapper mapper = new ObjectMapper();
      jGenerator.writeStartArray(); // [
  
      for (Event event : list) {
          String e = mapper.writeValueAsString(event);
          jGenerator.writeRaw(usage);
          // here, big hassles to write a comma to separate json objects, when the last object in the list is reached, no comma 
      }
  
      jGenerator.writeEndArray(); // ]
  
      jGenerator.close();
  
      System.out.println(out.toString());
  }
  </code></pre>
  
  <p>I am looking for something like:</p>
  
  <pre><code>generator.write(out, list)  
  </code></pre>
  
  <p>this directly convert the list to json array format and then write it to outputstream "out".</p>
  
  <p>even greedier:</p>
  
  <pre><code>generator.write(out, list1)
  
  generator.write(out, list2)
  </code></pre>
  
  <p>this will just convert/add in the list1, list2 into a single json array. then write it to "out"</p>