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
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));
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
链接地址: http://www.djcxy.com/p/48212.html上一篇: JSON.stringify自定义格式
下一篇: 如何在单独的行上记录每条JSON记录?
