使用FastJson进行JSON文件的读取和写入

构建JsonUtil类,包含两个方法,分别用于保存json信息和读取本地json。

/**
 * 读取与写入JSON文件
 * */

public class NodeJsonUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(NodeJsonUtil.class);

    // 将Nodes信息保存到本地json文件中
    public static void saveJson(ConvertDiagram jsonDiagram,String filePath){
        String writeString = JSON.toJSONString(jsonDiagram,SerializerFeature.PrettyFormat);

        LOGGER.info(writeString);
        BufferedWriter writer = null;
        File file = new File(filePath);
        //如果文件不存在则新建
        if (!file.exists()){
            try {
                file.createNewFile();
            }catch (IOException e){
                LOGGER.error(e.getMessage());
            }
        }
        //如果多次执行同一个流程,会导致json文件内容不断追加,在写入之前清空文件
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false),"UTF-8"));
            writer.write("");
            writer.write(writeString);
        }catch (IOException e){
            LOGGER.error(e.getMessage());
        }finally {
            try{
                if (writer != null){
                    writer.close();
                }
            }catch (IOException e){
                LOGGER.error(e.getMessage());
            }
        }
    }

    // 用于读取JSON文件
    public static readJsonFile(String filePath){
        BufferedReader reader = null;
        String readJson = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null){
                readJson += tempString;
            }
        }catch (IOException e){
            LOGGER.error(e.getMessage());
        }finally {
            if (reader != null){
                try {
                    reader.close();
                }catch (IOException e){
                    LOGGER.error(e.getMessage());
                }
            }
        }

        // 获取json
        try {
            JSONObject jsonObject = JSONObject.parseObject(readJson);
            System.out.println(JSON.toJSONString(jsonObject));
        }catch (JSONException e){
            LOGGER.error(e.getMessage());
        }
    }

}

相关文章

文章浏览阅读2.4k次。最近要优化cesium里的热力图效果,浏览...
文章浏览阅读1.2w次,点赞3次,收藏19次。在 Python中读取 j...
文章浏览阅读1.4k次。首字母缩略词 API 代表应用程序编程接口...
文章浏览阅读802次,点赞10次,收藏10次。解决一个JSON反序列...
文章浏览阅读882次。Unity Json和Xml的序列化和反序列化_uni...