I have a class, let\'s call it Cls, with some values in it. When I use a Gson instance declared with GsonBuilder.setPrettyPrinting().create()
and use that to se
Presumably, you're using something like this
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (FileWriter fileWriter = ...) {
gson.toJson(new Example(), Example.class, new JsonWriter(fileWriter));
}
The JsonWriter
wasn't created from the Gson
object and is therefore not configured to pretty print. You can, instead, retrieve a JsonWriter
instance from the Gson
object with newJsonWriter
gson.toJson(new Example(), Example.class, gson.newJsonWriter(fileWriter));
which
Returns a new JSON writer configured for the settings on this Gson instance.
This instance will pretty-print.
You can also set the indent
on your own instance
JsonWriter jsonWriter = new JsonWriter(fileWriter);
jsonWriter.setIndent(" ");
gson.toJson(new Example(), Example.class, jsonWriter);