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

3
  • Do any of the answers help from this -stackoverflow.com/questions/6185337/… Commented Apr 15, 2016 at 20:25
  • 1
    Quick and dirty, replace "\"},{\"" by "\"},\n{\"". Commented Apr 15, 2016 at 20:25
  • replace("},{", "},\n{") solve the prob .. Thanks @maraca for your help Commented Apr 16, 2016 at 8:20

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Are there any builtin ways of doing this? Adding a library just to print each entry on a new lines seems over the board.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.