【发布时间】: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()。