1. 程式人生 > >將List<Map<String, Object>>物件儲存在.json檔案中

將List<Map<String, Object>>物件儲存在.json檔案中


方法如下

 /**
     *@Author:   LXF
     *@Date:   10:26 2018/3/9
     *@Description:     將List<Map<String, Object>>物件儲存在.json檔案中
     */
    private static void mapPrintln(List<Map<String, Object>> list,String path) {
        if (list == null && list.size() == 0) {
            return;
        }
        Gson gson = new Gson();
        String jsonString = gson.toJson(list);
        inputFile(jsonString,path);// json檔案
        System.out.println(jsonString);// 列印
    }

    private static void inputFile(final String jsonString, final String path) {
        // TODO Auto-generated method stub
        new Thread(new Runnable() {

            public void run() {
                // TODO Auto-generated method stub
                WriteConfigJson(jsonString,path);
            }
        }).start();
    }

    /**
     * 輸出json檔案
     *
     * @param args
     */
    public static void WriteConfigJson(String args,String path) {
        //String src = "D:\\AA\\province.json";// 自定義檔案路徑

        File file = new File(path);

        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            file.delete();
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileWriter fw = new FileWriter(file, true);
            fw.write(args);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

其中,對於Gson物件需要匯入依賴包,通過maven匯入

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.2.4</version>
</dependency>