简体   繁体   中英

How to have each record of JSON on a separate line?

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

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/

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

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

为了获得易于阅读的json文件,您可以使用以下命令将ObjectMapper配置为缩进:

objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM