生成json文件寫入本地


 

public class Json {

    public static void main(String[] args) {

        String fullPath = null;
        //例如:fullPath="D:/myroot/test.json"

        // 生成json格式文件
        try {
            // 保證創建一個新文件
            File file = new File("E:\\json");
            if (!file.getParentFile().exists()) { // 如果父目錄不存在,創建父目錄
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,刪除舊文件
                file.delete();
            }
            file.createNewFile();

            //以下創建json格式內容
            //創建一個json對象,相當於一個容器
            JSONObject root = new JSONObject();
            root.put("name", "張三");
            root.put("age", 20);
            //假設身高是double,我們取小數點后一位
            double height = 185.5345;
            root.put("height", (double) (Math.round(height * 10) / 10.0));

            JSONArray array = new JSONArray();

            JSONObject major1 = new JSONObject();

            major1.put("job1", "worker");
            major1.put("job2", "doctor");

            JSONObject major2 = new JSONObject();
            major2.put("job3", "teacher");
            major2.put("job4", "student");

            array.add(major1);
            array.add(major2);
            root.put("major", array);

            //假設位置x,y都是double型的,現在對他們取整
            double x = 30.0045;
            double y = 30.1123;
            JSONObject houloc = new JSONObject();
            houloc.put("x", Math.round(x));
            houloc.put("y", Math.round(y));
            root.put("houseLocation", houloc);


            // 格式化json字符串
            String jsonString = formatJson(root.toString());

            // 將格式化后的字符串寫入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonString);
            write.flush();
            write.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 返回格式化JSON字符串。
     *
     * @param json 未格式化的JSON字符串。
     * @return 格式化的JSON字符串。
     */
    public static String formatJson(String json) {
        StringBuffer result = new StringBuffer();

        int length = json.length();
        int number = 0;
        char key = 0;

        // 遍歷輸入字符串。
        for (int i = 0; i < length; i++) {
            // 1、獲取當前字符。
            key = json.charAt(i);

            // 2、如果當前字符是前方括號、前花括號做如下處理:
            if ((key == '[') || (key == '{')) {
                // (1)如果前面還有字符,並且字符為“:”,打印:換行和縮進字符字符串。
                if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
                    result.append('\n');
                    result.append(indent(number));
                }

                // (2)打印:當前字符。
                result.append(key);

                // (3)前方括號、前花括號,的后面必須換行。打印:換行。
                result.append('\n');

                // (4)每出現一次前方括號、前花括號;縮進次數增加一次。打印:新行縮進。
                number++;
                result.append(indent(number));

                // (5)進行下一次循環。
                continue;
            }

            // 3、如果當前字符是后方括號、后花括號做如下處理:
            if ((key == ']') || (key == '}')) {
                // (1)后方括號、后花括號,的前面必須換行。打印:換行。
                result.append('\n');

                // (2)每出現一次后方括號、后花括號;縮進次數減少一次。打印:縮進。
                number--;
                result.append(indent(number));

                // (3)打印:當前字符。
                result.append(key);

                // (4)如果當前字符后面還有字符,並且字符不為“,”,打印:換行。
                if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
                    result.append('\n');
                }

                // (5)繼續下一次循環。
                continue;
            }

            // 4、如果當前字符是逗號。逗號后面換行,並縮進,不改變縮進次數。
            if ((key == ',')) {
                result.append(key);
                result.append('\n');
                result.append(indent(number));
                continue;
            }

            // 5、打印:當前字符。
            result.append(key);
        }

        return result.toString();
    }


    /**
     * 單位縮進字符串。
     */
    private static String SPACE = "   ";




    /**
     * 返回指定次數的縮進字符串。每一次縮進三個空格,即SPACE。
     *
     * @param number 縮進次數。
     * @return 指定縮進次數的字符串。
     */
    private static String indent(int number) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < number; i++) {
            result.append(SPACE);
        }
        return result.toString();
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM