Voicu Mihai Catalin
Voicu Mihai Catalin

Reputation: 21

How can I format this Json to put extra spaces and make it look readable?

 {"question":"Gli elementi della porta nel calcio sono pali, la
 traversa e…","includeInfo: ":false,"info: ":"info:
 ","answers":{"answerText":"Porta","correct: ":"0"}} {"answers:
 ":{"answerText":"Una palla","correct: ":"0"}} {"answers:
 ":{"answerText":"La rete","correct: ":"1"}

I already used .writerWithDefaultPrettyPrinter().writeValueAsString(j);, but it puts some unnecessary blocks, which I don`t need.

I use a resultSet to extract data from my DB and that data consists of questions and answers basically, but each question has different number of answers. The point is to make a readable Json with the questions and the proper number of answers. And, finally, the problem is that the data is quite large and prerryPrinting recognise the type of my data(like boolean, String, chars) and puts it before the element. If I`m using the basic JsonObject, the data looks is shown above. Is there any other way to construct my Json?

Upvotes: 0

Views: 767

Answers (1)

Mario Trucco
Mario Trucco

Reputation: 2011

You can use the JSONObject.toString(int indentFactor) method. It takes an int representing your desired indent factor.

Just a warning from the org.json java docs:

Warning: This method assumes that the data structure is acyclical.

Code sample:

        String in = "{\"question\":\"Gli elementi della porta nel calcio sono pali, la  traversa e…\",\"includeInfo: \":false,\"info: \":\"info:  \",\"answers\":{\"answerText\":\"Porta\",\"correct: \":\"0\"}} {\"answers:  \":{\"answerText\":\"Una palla\",\"correct: \":\"0\"}} {\"answers:  \":{\"answerText\":\"La rete\",\"correct: \":\"1\"}";
        JSONObject obj = new JSONObject(in);
        System.out.println(obj.toString(4));

Upvotes: 2

Related Questions