需求:将一个JSON对象写出到文件中,要求文件中的JSON数据带有简单的格式。代码的实现参考了Java算法中的栈处理括号匹配问题。好了,不多说了,下面是代码的实现。
代码:
1 package gemu.test.json; 2 3 import java.io.File; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 import java.io.Writer; 7 8 import net.sf.json.JSONArray; 9 10 public class WritePrettyJSON { 11 12 public static void main(String[] args) throws IOException { 13 14 File file = new File("D:/json.json"); 15 String jsonStr = "[{a:1,b:{b1:[{a:2},{a:1}]},c:3},{a:1},{b:1}]"; 16 // String jsonStr = "{a:1,b:{b1:[{a:2},{a:1}]},c:3,a:2,b:2}"; 17 JSONArray jsonObj = JSONArray.fromObject(jsonStr); 18 // JSONObject jsonObj = JSONObject.fromObject(jsonStr); 19 20 char[] stack = new char[1024]; // 存放括号,如 "{","}","[","]" 21 int top = -1; 22 23 String string = jsonObj.toString(); 24 StringBuffer sb = new StringBuffer(); 25 char[] charArray = string.toCharArray(); 26 for (int i = 0; i < charArray.length; i++) { 27 char c = charArray[i]; 28 if ('{' == c || '[' == c) { 29 stack[++top] = c; // 将括号添加到数组中,这个可以简单理解为栈的入栈 30 sb.append(charArray[i] + " "); 31 for (int j = 0; j <= top; j++) { 32 sb.append(" "); 33 } 34 continue; 35 } 36 if ((i + 1) <= (charArray.length - 1)) { 37 char d = charArray[i+1]; 38 if ('}' == d || ']' == d) { 39 top--; // 将数组的最后一个有效内容位置下标减 1,可以简单的理解为将栈顶数据弹出 40 sb.append(charArray[i] + " "); 41 for (int j = 0; j <= top; j++) { 42 sb.append(" "); 43 } 44 continue; 45 } 46 } 47 if (',' == c) { 48 sb.append(charArray[i] + " "); 49 for (int j = 0; j <= top; j++) { 50 sb.append(" "); 51 } 52 continue; 53 } 54 sb.append(c); 55 } 56 57 Writer write = new FileWriter(file); 58 write.write(sb.toString()); 59 write.flush(); 60 write.close(); 61 } 62 }