ab5qha
Last Updated: July 22, 2017
·
21.28K
· 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

Say Thanks
Respond
Awesome Job

6b8b6d7e 76ea 11e7 971b 140e127bbcbb
Senior DevOps Engineer
·
New York City (Midtown)
·
Full Time