Streaming to write Json
gson, io, java, json, stream
Solution
You can use Gson to stream your list like this:
private void myWriter(List<JsonObject> jsonObjectHolder, Gson gson) throws IOException
{
JsonWriter writer = new JsonWriter(new FileWriter(new File("items.json")));
writer.beginArray();
for (JsonObject jsonObject : jsonObjectHolder)
{
gson.toJson(jsonObject, writer);
}
writer.endArray();
writer.close();
}
This assumes you have a `Gson` instance that you can use. If you do not, you can use `writer.beginObject()` with `writer.endObject()` and manually add properties to the writer, but I wouldn't recommend this because you've already done the work of building a `JsonObject`.
Problem
I have a large set of `JsonObject`s inside a `ArrayList`. I need to add these `JsonObject`s into a `JsonArray` and write it into a file. I am using `Gson` and below is my code. ``` private void myWriter(List<JsonObject> jsonObjectHolder, int number) throws IOException { System.out.println("Starting to write the JSON File"); //Add everything into a JSONArray JsonArray jsonArrayNew = new JsonArray(); for(int i=0;i<jsonObjectHolder.size();i++) { //System.out.println("inside array: "+i); JsonObject o = jsonObjectHolder.get(i); System.out.println("inside array "+i+": "+o.get("title")); jsonArrayNew.add(jsonObjectHolder.get(i)); } System.out.println("Size: "+jsonArrayNew.size()); //Write it to the File File file= new File("items.json"); FileWriter fw = new FileWriter(file);; fw.write(jsonArrayNew.toString()); fw.flush(); fw.close(); System.out.println("outside array"); } ``` I don't like this way. The `ArrayList` holds lot of data and the way I write could generate `OutOfMemoryError`. Instead, I would like to Stream and write these to the file. Update According to the answer of SO user "Alden", here how I edited the code. ``` private void myWriter(List<JsonObject> jsonObjectHolder) throws IOException { JsonWriter writer = new JsonWriter(new FileWriter(new File("items.json"))); Gson gson = new Gson(); writer.beginArray(); for (JsonObject jsonObject : jsonObjectHolder) { gson.toJson(jsonObject, writer); } writer.endArray(); writer.close(); } ``` Please let me know whether this is the correct way of doing it.