In the process of interface testing, most data interaction uses json format, but the effect of json output from console is far less beautiful than that of browser plug-in. After searching for some information, I decided to write a formatting method to output json information to the console. After some attempts, it has been completed. Share as follows:
/** * Output json * * @param jsonObject json Format response entity */ public static JSONObject output(JSONObject jsonObject) { if (MapUtils.isEmpty(jsonObject)) { output("json The object is empty!"); return jsonObject; } String start = SourceCode.getManyString(SPACE_1, 4); String jsonStr = jsonObject.toString();// First transform json object into string object jsonStr = jsonStr.replaceAll("\\\\/", OR); int level = 0;// User tag hierarchy StringBuffer jsonResultStr = new StringBuffer("> ");// Create a new stringbuffer object, and the user receives the converted string string string for (int i = 0; i < jsonStr.length(); i++) {// Loop through each character char piece = jsonStr.charAt(i);// Get the current character // If the last character is a broken line, the first line is excluded by adding a marker at the beginning of the line according to the level value. if (i != 0 && '\n' == jsonResultStr.charAt(jsonResultStr.length() - 1)) { for (int k = 0; k < level; k++) { jsonResultStr.append(start); } } switch (piece) { case ',': // If it is ",", it will break the line. char last = jsonStr.charAt(i - 1); if ("\"0123456789le]}".contains(last + EMPTY)) { jsonResultStr.append(piece + LINE); } else { jsonResultStr.append(piece); } break; case '{': case '[': // If the character is {or [, then line break, level plus 1 jsonResultStr.append(piece + LINE); level++; break; case '}': case ']': // If it is} or], break the line, level minus 1 jsonResultStr.append(LINE); level--; for (int k = 0; k < level; k++) { jsonResultStr.append(start); } jsonResultStr.append(piece); break; default: jsonResultStr.append(piece); break; } } output(LINE + "↘ ↘ ↘ ↘ ↘ ↘ ↘ ↘ json ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙" + LINE + jsonResultStr.toString().replaceAll(LINE, LINE + "> ") + LINE + "↘ ↘ ↘ ↘ ↘ ↘ ↘ ↘ json ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙ ↙"); return jsonObject; }
Update the output display effect:
Note: There is "in JSON data", "This situation and value non-string (number and null or science and technology method) may have some display anomalies, and value value itself is a string of JSON data will also be treated as json. Generally speaking, it is enough and the effect is satisfactory.
Selection of previous articles
- One line of java code prints a heart
- Linux performance monitoring software netdata Chinese version
- Interface Test Code Coverage (jacoco) Scheme Sharing
- Performance testing framework
- How to Enjoy Performance Testing on Linux Command Line Interface
- Graphic HTTP Brain Map
- Writing to everyone about programming thinking
- Test JVM Command Brain Map