Atanu Atanu - 1 year ago 51
Java Question

Json Object Array Write in Java line by line

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


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