Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing pretty print json output to fileoutput stream with GSON JsonWriter [duplicate]

Tags:

java

json

gson

I am having hard time in writing pretty print json string on file using Gson library. Code I am using is here:

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

Here stream is nothing but a file output stream. Even though I have enabled the pretty printing but still I am getting unformatted json string on file.

Any help is appreciated.

like image 642
BigD Avatar asked Feb 27 '15 06:02

BigD


1 Answers

You can simply enable the pretty print by setting the indent.

jsonWriter.setIndent("  ");
like image 141
Leo Wang Avatar answered Nov 14 '22 21:11

Leo Wang