2

I have a Array with some value when i store that array i got result like this

[{"id":56678,"Name":"Rehman Agarwal"},{"id":66849,"Name":"Rasul Guha"}]

means in a single line.

but I just want to get output like

[{"id":56678,"Name":"Rehman Agarwal"},
{"id":66849,"Name":"Rasul Guha"}]

new line after JSON object ..

How to do it ?

EDIT : i use JSONObject && JSONArray for create json Object and array respectively

Atanu
  • 337
  • 2
  • 14

1 Answers1

5

Using gson library you can pretty print your json strings like below -

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;
}

And call it like below -

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);
}
Raman Shrivastava
  • 2,923
  • 15
  • 26
  • Are there any builtin ways of doing this? Adding a library just to print each entry on a new lines seems over the board. – Timmay May 23 '19 at 12:18