I have a large set JsonObjectinside a ArrayList. I need to add these JsonObjectto JsonArrayand write them to a file. I use 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");
JsonArray jsonArrayNew = new JsonArray();
for(int i=0;i<jsonObjectHolder.size();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());
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 do not like it. ArrayListcontains a lot of data, and the way I write can generate OutOfMemoryError. Instead, I would like to Stream and write them to a file.
Update
According to the answer of SO "Alden" user, here is 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 if this is done correctly.
source
share