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

ε祈祈猫儿з 提交于 2019-12-19 10:54:13

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/54448533/why-will-gson-pretty-print-to-the-console-but-not-the-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!