我很难用Gson库在文件上写漂亮的print json字符串。我正在使用的代码在这里:
Gson gs = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
JsonWriter jsonWriter = null;
try {
jsonWriter = new JsonWriter(new OutputStreamWriter(stream, "UTF-8"));
jsonWriter.beginArray();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (Feed feed : feeds) {
gs.toJson(feed, Feed.class, jsonWriter);
}
try {
jsonWriter.endArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
jsonWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
这里的流只是一个文件输出流。即使我已经启用了漂亮的打印,但我仍然在文件中获得未格式化的json字符串。
感谢任何帮助。
答案 0 :(得分:8)
您可以通过设置缩进来启用漂亮的打印。
jsonWriter.setIndent(" ");