如何格式化这个Json以放置额外的空格并使其看起来可读?

时间:2016-04-21 09:59:37

标签: java json

 {"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"}

我已经使用了.writerWithDefaultPrettyPrinter().writeValueAsString(j);,但它会放置一些不必要的块,这些块我不需要。

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?

1 个答案:

答案 0 :(得分:1)

您可以使用JSONObject.toString(int indentFactor)方法。需要int表示您所需的缩进系数。

来自org.json java docs的警告:

  

警告:此方法假定数据结构是非周期性的。

代码示例:

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