用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);
}

你可能感兴趣的:(编程)