zoukankan      html  css  js  c++  java
  • Java 读取Json文件内容

      读取json文件为String类型:

    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    
    import java.io.*;
    
    /**
     * Json读取工具类
     */
    public class JsonUtil {
    
        private static final Logger logger = LogManager.getLogger(JsonUtil.class);
    
        /**
         * 读取json文件
         * @param fileName json文件名
         * @return 返回json字符串
         */
        public String readJsonFile(File jsonFile) {
            String jsonStr = "";
            logger.info("————开始读取" + jsonFile.getPath() + "文件————");
            try {
                //File jsonFile = new File(fileName);
                FileReader fileReader = new FileReader(jsonFile);
                Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
                int ch = 0;
                StringBuffer sb = new StringBuffer();
                while ((ch = reader.read()) != -1) {
                    sb.append((char) ch);
                }
                fileReader.close();
                reader.close();
                jsonStr = sb.toString();
                logger.info("————读取" + jsonFile.getPath() + "文件结束!————");
                return jsonStr;
            } catch (Exception e) {
                logger.info("————读取" + jsonFile.getPath() + "文件出现异常,读取失败!————");
                e.printStackTrace();
                return null;
            }
        }
    }
    

      将读取出来的JSON文件内容从String转为Map:

    import com.alibaba.fastjson.JSON;
    
    String jsonStr = jsonUtil.readJsonFile(file);
    Map jsonMap = (Map) JSON.parse(jsonStr);
    

      

  • 相关阅读:
    vim常用命令
    转:CRF++总结1
    转:CRF++总结2
    并查集算法程序
    CRF++使用小结(转)
    并查集算法程序
    C#winform 画图
    转:字符识别
    转:A Survey On Relation Extraction
    转:生产计划问题
  • 原文地址:https://www.cnblogs.com/Big-Boss/p/11252095.html
Copyright © 2011-2022 走看看