package com.sensor.sellCabinet.util; import java.io.File; import java.io.FileOutputStream; public class JsonPrint { private static String getLevelStr(int level) { StringBuffer levelStr = new StringBuffer(); for (int levelI = 0; levelI < level; levelI++) { levelStr.append(" "); } return levelStr.toString(); } public static void print(String filePath,String s){ int level = 0; //存放格式化的json字符串 StringBuffer jsonForMatStr = new StringBuffer(); for(int index=0;index<s.length();index++)//将字符串中的字符逐个按行输出 { //获取s中的每个字符 char c = s.charAt(index); // System.out.println(s.charAt(index)); //level大于0并且jsonForMatStr中的最后一个字符为 ,jsonForMatStr加入 if (level > 0 && ' ' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) { jsonForMatStr.append(getLevelStr(level)); // System.out.println("123"+jsonForMatStr); } //遇到"{"和"["要增加空格和换行,遇到"}"和"]"要减少空格,以对应,遇到","要换行 switch (c) { case '{': case '[': jsonForMatStr.append(c + " "); level++; break; case ',': jsonForMatStr.append(c + " "); break; case '}': case ']': jsonForMatStr.append(" "); level--; jsonForMatStr.append(getLevelStr(level)); jsonForMatStr.append(c); break; default: jsonForMatStr.append(c); break; } } write(filePath,jsonForMatStr); } /** * 写入文件 */ private static void write(String filePath,StringBuffer val) { try { File file = new File(filePath); if(!file.exists()){ file.createNewFile(); } FileOutputStream stream = new FileOutputStream(file, true); stream.write((val+(System.getProperty("line.separator"))).getBytes()); stream.flush(); stream.close(); } catch (Exception e) { // TODO: handle exception } } }