Last Updated: September 29, 2021
·
100.6K
· kencoder

Convert JSON string to Pretty Print (Java, Gson)

This is the method to convert a JSON string to a pretty print version.

/**
   * Convert a JSON string to pretty print version
   * @param jsonString
   * @return
   */
  public static String toPrettyFormat(String jsonString) 
  {
      JsonParser parser = new JsonParser();
      JsonObject json = parser.parse(jsonString).getAsJsonObject();

      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String prettyJson = gson.toJson(json);

      return prettyJson;
  }

The way to use it:

@Test
public void testPrettyPrint()
{
    String compactJson = "{\"playerID\":1234,\"name\":\"Test\",\"itemList\":[{\"itemID\":1,\"name\":\"Axe\",\"atk\":12,\"def\":0},{\"itemID\":2,\"name\":\"Sword\",\"atk\":5,\"def\":5},{\"itemID\":3,\"name\":\"Shield\",\"atk\":0,\"def\":10}]}";

    String prettyJson = toPrettyFormat(compactJson);

    System.out.println("Compact:\n" + compactJson);
    System.out.println("Pretty:\n" + prettyJson);
}

Sample Output:

Picture