ab5qha
Last Updated: April 27, 2017
·
16.62K
· kenlakoo
2a92ad89c8bd4e8b45edc8f363e18aa3 normal

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

1 Response
Add your response

28876

very nice article, I also want to suggest a tool which can do this https://jsonformatter.org/json-pretty-print

about 1 hour ago ·