Json系列之三 让你打印完美的json格式

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





郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。