Last Updated: May 19, 2018
· 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:

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:


Say Thanks

1 Response
Add your response


Just read article which converts JSON string to object using Javascript. https://codeblogmoney.com/convert-string-to-json-using-javascript/

9 days ago ·