1. 程式人生 > >Java生成並匯出Json檔案

Java生成並匯出Json檔案

將一個list集合轉換成json檔案並匯出:

複製程式碼

     
資料集合:
    List<Object> agencyList = new ArrayList<Object>();
        Map<String, Object> agencyMap = new HashMap<>();
        agencyMap.put("agencyName",agencyName);
        agencyMap.put("agencyAddress", agencyAddress);
        agencyMap.put("companyName", companyName);
        agencyMap.put("logoImageId", logoImageId);
        agencyMap.put("auctionAddress", agencyAuctionAddress);
        agencyMap.put("logoImage", logoImage);
        agencyList.add(agencyMap);

複製程式碼

 

    
將集合資料轉換為json字串(當然map集合亦可以):
     JSONArray jsonObject = JSONArray.fromObject(agencyList);
        String jsonString1 = jsonObject.toString();
        CreateFileUtil.createJsonFile(jsonString1, "/fileStorage/download/json", "agency");

 

複製程式碼

public class CreateFileUtil {
    /**
     * 生成.json格式檔案
     */
    public static boolean createJsonFile(String jsonString, String filePath, String fileName) {
        // 標記檔案生成是否成功
        boolean flag = true;

        // 拼接檔案完整路徑
        String fullPath = filePath + File.separator + fileName + ".json";

        // 生成json格式檔案
        try {
            // 保證建立一個新檔案
            File file = new File(fullPath);
            if (!file.getParentFile().exists()) { // 如果父目錄不存在,建立父目錄
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,刪除舊檔案
                file.delete();
            }
            file.createNewFile();

            if(jsonString.indexOf("'")!=-1){  
                //將單引號轉義一下,因為JSON串中的字串型別可以單引號引起來的  
                jsonString = jsonString.replaceAll("'", "\\'");  
            }  
            if(jsonString.indexOf("\"")!=-1){  
                //將雙引號轉義一下,因為JSON串中的字串型別可以單引號引起來的  
                jsonString = jsonString.replaceAll("\"", "\\\"");  
            }  
              
            if(jsonString.indexOf("\r\n")!=-1){  
                //將回車換行轉換一下,因為JSON串中字串不能出現顯式的回車換行  
                jsonString = jsonString.replaceAll("\r\n", "\\u000d\\u000a");  
            }  
            if(jsonString.indexOf("\n")!=-1){  
                //將換行轉換一下,因為JSON串中字串不能出現顯式的換行  
                jsonString = jsonString.replaceAll("\n", "\\u000a");  
            }  
            
            // 格式化json字串
            jsonString = JsonFormatTool.formatJson(jsonString);

            // 將格式化後的字串寫入檔案
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonString);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        // 返回是否成功的標記
        return flag;
    }
       
}

複製程式碼

 

 

複製程式碼

public class JsonFormatTool {
    /**
     * 單位縮排字串。
     */
    private static String SPACE = "   ";

    /**
     * 返回格式化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();
    }

    /**
     * 返回指定次數的縮排字串。每一次縮排三個空格,即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();
    }
}

複製程式碼

 

 

 

當然其中涉及到轉義字元處理的問題。