Jacob
Jacob

Reputation: 217

Why will Gson pretty-print to the console, but not the file?

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 serialize a Cls object and print the resulting JSON string to console, I get it nicely formatted, like so:

{
    "foo":"bar",
    "foo2":["b1","b2"],
    "foo3":12
}

This is all well and good, but when I then create a JsonWriter (from a FileWriter with an absolute path) and use the Gson instance's toJson(Object, Class, JsonWriter) method with Cls, the resulting file does NOT get formatted nicely. It instead looks like this:

{"foo":"bar","foo2":["b1","b2"],"foo3":12}

This defeats the whole point of pretty printing. Why is it doing this, and how can I make it stop?

Upvotes: 2

Views: 1179

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280167

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);

Upvotes: 6

Related Questions