2

When I use JSONArray and JSONObject to generate a JSON, whole JSON will be generated in one line. How can I have each record on a separate line?

It generates like this:

 [{"key1":"value1","key2":"value2"}]

I need it to be like following:

 [{
    "key1":"value1",
    "key2":"value2"
    }]
Sarath
  • 2,318
  • 1
  • 12
  • 24
Jack
  • 6,430
  • 27
  • 80
  • 151

4 Answers4

2

You can use Pretty Print JSON Output (Jackson).

Bellow are some examples

  1. Convert Object and print its output in JSON format.

     User user = new User();
     //...set user data
     ObjectMapper mapper = new ObjectMapper();
     System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
    
  2. Pretty Print JSON String

     String test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"myname\"}";
    
     Object json = mapper.readValue(test, Object.class);    
     System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
    

Reference : http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/

Rockstar
  • 2,228
  • 3
  • 20
  • 39
2

You may use of the google-gson library for beautifying your JSON string. You can download the library from here
Sample code :

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);

OR

you can use org.json
Sample code :

JSONTokener tokener = new JSONTokener(uglyJsonString); //tokenize the ugly JSON string
JSONObject finalResult = new JSONObject(tokener); // convert it to JSON object
System.out.println(finalResult.toString(4)); // To string method prints it with specified indentation.

Refer answer from this post : Pretty-Print JSON in Java

Community
  • 1
  • 1
Rahul Vishwakarma
  • 996
  • 5
  • 17
  • 35
  • This doesn't work for arrays (which was the original requirement). It does pretty print objects with line breaks, but not objects contained within an outer array structure. – David Ford Feb 26 '18 at 23:08
0

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level

and please refer this : https://stackoverflow.com/a/2614874/3164682

you can also beautify your string online here.. http://codebeautify.org/jsonviewer

Community
  • 1
  • 1
Sarath
  • 2,318
  • 1
  • 12
  • 24
0

For gettting a easy to read json file you can configure the ObjectMapper to Indent using the following:

objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

e-Euler
  • 1
  • 3