标签:
public static String format(String jsonStr) { int level = 0; StringBuffer jsonForMatStr = new StringBuffer(); for(int i=0;i<jsonStr.length();i++){ char c = jsonStr.charAt(i); if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){ jsonForMatStr.append(getLevelStr(level)); } switch (c) { case '{': case '[': jsonForMatStr.append(c+"\n"); level++; break; case ',': jsonForMatStr.append(c+"\n"); break; case '}': case ']': jsonForMatStr.append("\n"); level--; jsonForMatStr.append(getLevelStr(level)); jsonForMatStr.append(c); break; default: jsonForMatStr.append(c); break; } } return jsonForMatStr.toString(); } private static String getLevelStr(int level){ StringBuffer levelStr = new StringBuffer(); for(int levelI = 0;levelI<level ; levelI++){ levelStr.append("\t"); } return levelStr.toString(); }
通过以上format代码,可以让你的json打印完美无缺
例子仍然是bean to json博文中的例子
{ "addresses":[ { "address":"address1", "sameTest":[ { "addresses":[ ], "age":0, "attrs":null, "baseAddress":null, "birthDay":null, "emptyStr":"", "live":false, "name":"sameName", "nullStr":"", "sameTest":null } ] }, { "address":"address2", "sameTest":[ ] } ], "age":1, "attrs":{ "key2":"value2", "key1":"value1" }, "baseAddress":{ "address":"base address", "sameTest":[ ] }, "birthDay":{ "date":10, "day":2, "hours":11, "minutes":11, "month":1, "seconds":4, "time":1423537864497, "timezoneOffset":-480, "year":115 }, "emptyStr":"", "live":true, "name":"xxx", "nullStr":"", "sameTest":{ "sameName2":"sameNamevalue2", "sameName1":"sameNamevalue1" } }
标签:
原文地址:http://blog.csdn.net/harrison2010/article/details/43701631