为什么Gson会漂亮地打印到控制台,而不打印到文件? [英] Why will Gson pretty-print to the console, but not the file?

查看:255
本文介绍了为什么Gson会漂亮地打印到控制台,而不打印到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我们称它为Cls,其中有一些值.当我使用用GsonBuilder.setPrettyPrinting().create()声明的Gson实例并将其序列化一个Cls对象并将结果JSON字符串打印到控制台时,我得到了格式良好的格式,如下所示:

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
}

这一切都很好,但是当我然后创建一个JsonWriter(从具有绝对路径的FileWriter)并使用带有Cls的Gson实例的toJson(Object, Class, JsonWriter)方法时,生成的文件的格式不会很好.相反,它看起来像这样:

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?

推荐答案

大概您正在使用类似的东西

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

JsonWriter不是从Gson对象创建的,因此未配置为漂亮打印.您可以改为使用

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

其中

返回为此Gson实例上的设置配置的新JSON编写器.

Returns a new JSON writer configured for the settings on this Gson instance.

此实例将漂亮打印.

您还可以在自己的实例上设置indent

You can also set the indent on your own instance

JsonWriter jsonWriter = new JsonWriter(fileWriter);
jsonWriter.setIndent("  ");
gson.toJson(new Example(), Example.class, jsonWriter);

这篇关于为什么Gson会漂亮地打印到控制台,而不打印到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆