使用GSON JsonWriter将漂亮的print json输出写入fileoutput流

Big*_*igD 5 java json gson

我很难用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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

这里的流只是一个文件输出流.即使我已经启用了漂亮的打印,但我仍然在文件中获取未格式化的json字符串.

任何帮助表示赞赏.

小智 8

您可以通过设置缩进来启用漂亮的打印.

jsonWriter.setIndent("  ");
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案.使用`JsonWriter`时会忽略`GsonBuilder.setPrettyPrinting()`调用. (2认同)