1. 程式人生 > >用fastjson將物件的列表轉換成json格式,並讀寫.json檔案

用fastjson將物件的列表轉換成json格式,並讀寫.json檔案

import com.alibaba.fastjson.JSON;
import org.json.JSONArray;
import org.json.JSONObject;

public static void main(String[] args) {
        // 返回的結果
        JSONObject result = new JSONObject();

        // 學生
        JSONArray studentJsonArray = new JSONArray(JSON.toJSONString(studentList));
        result.put("studentMap", studentJsonArray);
        
        // 時間表
        JSONObject pointTableJsonObject = new JSONObject(JSON.toJSONString(pointTable));
        result.put("pointTable", pointTableJsonObject);
     
        try {
            writeFile("D:\\8.json", result.toString());
//            ReadFile("D:\\8.json");
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }

}

/**
 * 寫檔案到.Json
 * @param filePath
 * @param sets
 * @throws IOException
 */
public static void writeFile(String filePath, String sets)
        throws IOException {
    FileWriter fw = new FileWriter(filePath);
    PrintWriter out = new PrintWriter(fw);
    out.write(sets);
    out.println();
    fw.close();
    out.close();
}

/**
 * 讀Json檔案
 * @param path
 * @return
 */
public static Object ReadFile(String path) {
    File file = new File(path);
    BufferedReader reader = null;
    String laststr = "";
    try {
        reader = new BufferedReader(new FileReader(file));
        String tempString = null;
        while ((tempString = reader.readLine()) != null) {
            laststr = laststr + tempString;
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e1) {
            }
        }
    }
    return JSON.parse(laststr);
}