宇筱博客

  • 解决办法
  • 学无止境
  • 记录时光
  • 百宝箱
宇筱博客
点滴记忆,汇聚成海。
  1. 首页
  2. 解决办法
  3. 正文

将JSON对象带有格式的写出到文件中

2017年1月7日 745点热度 0人点赞 0条评论
package gemu.test.json;  
  
import java.io.File;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.io.Writer;  
  
import net.sf.json.JSONArray;  
  
public class WritePrettyJSON {  
  
    public static void main(String[] args) throws IOException {  
          
        File file = new File("D:/json.json");  
        String jsonStr = "[{a:1,b:{b1:[{a:2},{a:1}]},c:3},{a:1},{b:1}]";  
//      String jsonStr = "{a:1,b:{b1:[{a:2},{a:1}]},c:3,a:2,b:2}";  
        JSONArray jsonObj = JSONArray.fromObject(jsonStr);  
//      JSONObject jsonObj = JSONObject.fromObject(jsonStr);  
          
        char[] stack = new char[1024]; // 存放括号,如 "{","}","[","]"  
        int top = -1;  
          
        String string = jsonObj.toString();  
        StringBuffer sb = new StringBuffer();  
        char[] charArray = string.toCharArray();  
        for (int i = 0; i < charArray.length; i++) {  
            char c = charArray[i];  
            if ('{' == c || '[' == c) {  
                stack[++top] = c; // 将括号添加到数组中,这个可以简单理解为栈的入栈  
                sb.append(charArray[i] + "\n");  
                for (int j = 0; j <= top; j++) {  
                    sb.append("\t");  
                }  
                continue;  
            }  
            if ((i + 1) <= (charArray.length - 1)) {  
                char d = charArray[i+1];  
                if ('}' == d || ']' == d) {  
                    top--; // 将数组的最后一个有效内容位置下标减 1,可以简单的理解为将栈顶数据弹出  
                    sb.append(charArray[i] + "\n");  
                    for (int j = 0; j <= top; j++) {  
                        sb.append("\t");  
                    }  
                    continue;  
                }  
            }  
            if (',' == c) {  
                sb.append(charArray[i] + "\n");  
                for (int j = 0; j <= top; j++) {  
                    sb.append("\t");  
                }  
                continue;  
            }  
            sb.append(c);  
        }  
          
        Writer write = new FileWriter(file);  
        write.write(sb.toString());  
        write.flush();  
        write.close();  
    }  
}  

原文链接:http://blog.csdn.net/gemuandyou/article/details/46737879

标签: 暂无
最后更新:2017年1月7日

小渔民

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2025 宇筱博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

豫ICP备15017825号-2