• 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);
    

      

  • 相关阅读:
    使用contentProvider
    创建Sqlite数据库(一)
    AIDL实现进程间通信
    Messenger实现进程间通信(IPC)
    Serializable使用
    Parcelable使用(二)
    STAR法则
    Python系列-------基本语法
    前端随心记---------面试题集
    前端随心记---------惟客科技面试
  • 原文地址:https://www.cnblogs.com/Big-Boss/p/11252095.html
Copyright © 2020-2023  润新知