Search code examples
javajsonpretty-printjson-simple

Pretty-Print JSON in Java


I'm using and I need to pretty-print JSON data (make it more human readable).

I haven't been able to find this functionality within that library. How is this commonly achieved?


Solution

  • Google's GSON can do this in a nice way:

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonParser jp = new JsonParser();
    JsonElement je = jp.parse(uglyJsonString);
    String prettyJsonString = gson.toJson(je);
    

    or since it is now recommended to use the static parse method from JsonParser you can also use this instead:

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonElement je = JsonParser.parseString​(uglyJsonString);
    String prettyJsonString = gson.toJson(je);
    

    Here is the import statement:

    import com.google.gson.*;
    

    Here is the Gradle dependency:

    implementation 'com.google.code.gson:gson:2.8.7'