【问题标题】:Java Json beautifying on saveJava Json在保存时美化
【发布时间】:2018-07-04 03:42:30
【问题描述】:

我正在将播放器保存到这样的 .json 文件中:

public static void savePlayer(Player player) {
    final String username = player.getUsername();
    final byte[] json = new Gson().toJson(player).getBytes();
    final String path = "pack/players/" + username;

    try {
        Files.write(Paths.get(path + "/data.json"), json, StandardOpenOption.CREATE);   
        logger.info("Successfully SAVED player [username=%s]!", username);
    } catch (IOException e) {
        e.printStackTrace();
    }
}   

我正在使用这个 Eclipse JSON 编辑器插件来查看 json 文件:https://sourceforge.net/projects/eclipsejsonedit/

但是看文件的时候,全部压缩在一行,没有美化。

生成的一行json代码是这样打印的(而不是美化的):

{"inventory":{"data":[null]},"equipment":{"data":[null]},"playerCredentials":{"username":"kay","password":"password"},"attribute":{}}

如何在保存之前美化代码?

【问题讨论】:

  • 您需要使用 GsonBuilder 设置该设置。
  • @vandench 甚至不知道该类可以格式化,我在构建器中使用什么方法?我没有看到任何接受参数字符串?
  • 您使用一种构建器方法来设置属性,它被称为漂亮打印。调用 build 后,您将获得一个配置好的 Gson 对象,然后您可以使用该对象生成 json。
  • 函数是setPrettyPrinting()

标签: java json syntax gson


【解决方案1】:

由于你使用的是 Gson,你可以使用他们的 prettyPrinting 并创建一个新的 Gson 对象

Gson gson = new GsonBuilder().setPrettyPrinting().create();

然后从中创建一个字符串对象

String output = gson.toJson(json);

如果您使用 FileWriter,您可以简单地使用该字符串写入文件。

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 2011-07-24
    • 1970-01-01
    • 2020-06-11
    • 2018-01-18
    • 1970-01-01
    • 2012-02-24
    • 2021-03-29
    • 1970-01-01
    相关资源
    最近更新 更多