工作中进行http相关接口测试时经常会收到返回的json数据,因为没有格式化输入到控制台后看起来很不直观。
早上写了一个小工具类,对这JSON串进行格式化输出,代替System.out.print
package MyTest; /** * 格式化输入工具类 * @author lizhgb * @date 2015-10-14 * */ public final class FormatUtil { /** * 打印输入到控制台 * @param jsonStr * @author lizhgb * @Date 2015-10-14 下午1:17:22 */ public static void printJson(String jsonStr){ System.out.println(formatJson(jsonStr)); } /** * 格式化 * @param jsonStr * @return * @author lizhgb * @Date 2015-10-14 下午1:17:35 */ public static String formatJson(String jsonStr) { if (null == jsonStr || "".equals(jsonStr)) return ""; StringBuilder sb = new StringBuilder(); char last = ‘\0‘; char current = ‘\0‘; int indent = 0; for (int i = 0; i < jsonStr.length(); i++) { last = current; current = jsonStr.charAt(i); switch (current) { case ‘{‘: case ‘[‘: sb.append(current); sb.append(‘\n‘); indent++; addIndentBlank(sb, indent); break; case ‘}‘: case ‘]‘: sb.append(‘\n‘); indent--; addIndentBlank(sb, indent); sb.append(current); break; case ‘,‘: sb.append(current); if (last != ‘\\‘) { sb.append(‘\n‘); addIndentBlank(sb, indent); } break; default: sb.append(current); } } return sb.toString(); } /** * 添加space * @param sb * @param indent * @author lizhgb * @Date 2015-10-14 上午10:38:04 */ private static void addIndentBlank(StringBuilder sb, int indent) { for (int i = 0; i < indent; i++) { sb.append(‘\t‘); } } }
测试:
@Test public void jsonPrintTest2() { String str = "{\"content\":\"this is the msg content.\",\"tousers\":\"user1|user2\",\"msgtype\":\"texturl\",\"appkey\":\"test\",\"domain\":\"test\"," + "\"system\":{\"wechat\":{\"safe\":\"1\"}},\"texturl\":{\"urltype\":\"0\",\"user1\":{\"spStatus\":\"user01\",\"workid\":\"work01\"},\"user2\":{\"spStatus\":\"user02\",\"workid\":\"work02\"}}}"; FormatUtil.printJson(str); }
输出:
{ "content":"this is the msg content.", "tousers":"user1|user2", "msgtype":"texturl", "appkey":"test", "domain":"test", "system":{ "wechat":{ "safe":"1" } }, "texturl":{ "urltype":"0", "user1":{ "spStatus":"user01", "workid":"work01" }, "user2":{ "spStatus":"user02", "workid":"work02" } } }
时间: 2024-11-09 02:06:22