I am having hard time in writing pretty print json string on file using Gson library. Code I am using is here:
Gson gs = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
JsonWriter jsonWriter = null;
try {
jsonWriter = new JsonWriter(new OutputStreamWriter(stream, "UTF-8"));
jsonWriter.beginArray();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (Feed feed : feeds) {
gs.toJson(feed, Feed.class, jsonWriter);
}
try {
jsonWriter.endArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
jsonWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Here stream is nothing but a file output stream. Even though I have enabled the pretty printing but still I am getting unformatted json string on file.
Any help is appreciated.
You can simply enable the pretty print by setting the indent.
jsonWriter.setIndent(" ");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With