Previously my code was just this:
objJson = gson.toJson(objList);
return objJson;
And I got the string JSON with that return value.
But then I started getting famous Out Of Memory errors when the JSON becomes too large.
Then I followed the following post that converts the list of objects into JSON String in an efficient way that OOM errors will be no more:
https://sites.google.com/site/gson/streaming
So, I have followed the above approach here:
public String writeJsonStream(List<MyObj> objList) throws IOException {
ByteArrayOutputStream baos=new ByteArrayOutputStream();
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(baos,"UTF-8");
JsonWriter writer = new JsonWriter(outputStreamWriter);
writer.setIndent(" ");
writer.beginArray();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
for (MyObj myobj : objList) {
gson.toJson(myobj, MyObj.class, writer);
}
String objJson = writer.toString();
writer.endArray();
writer.close();
return objJson;
}
But this returning object com.google.gson.stream.JsonWriter@6a9454cd.
The method gson.toJson(myobj, MyObj.class, writer); is of type void and doesn't returns JSON string. So how can I get the JSON string in this case?