zoukankan      html  css  js  c++  java
  • json 文件打读取

    1。获取文件路径

    /*
             * BookController.class.getClassLoader().getResource("static/json/book_nav.json").getPath() 获取当期运行时的项目json文件路径
             */
            JSONObject json = JsonResourceUtils.getJsonObjFromResource
                    (BookController.class.getClassLoader().getResource("static/json/book_nav.json").getPath());
        
            Set<Entry<String, Object>> entrySets=json.entrySet();
            /*
             * 取出json数据
             */
            for(Entry<String, Object> entrySet: entrySets)
            {
                if(entrySet.getKey().equals("bookNavs"))
                model.addAttribute("bookNavs",entrySet.getValue());
            }

    2.读取json文件

    package com.feilong.reptile.util;
    
    import java.io.File;
    import java.io.IOException;
    
    import org.apache.commons.io.FileUtils;
    import org.apache.log4j.Logger;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    
    public class JsonResourceUtils{
        private static Logger logger = Logger.getLogger(JsonResourceUtils.class);
        
        /*
         * filePath文件路径
         * @param filePath
         */
        public static JSONObject getJsonObjFromResource(String filePath)
        {
            
            
                JSONObject json = null;
    
                if (!filePath.contains(".json")) {
                    filePath += ".json";
                }
                    File file = new File(filePath);
                    if (file.exists()) {
                        String content=null;
                        try {
                            content = FileUtils.readFileToString(file, "UTF-8");
                        } catch (IOException e) {    
                            e.printStackTrace();
                             logger.info("readFileToString: " + e.getMessage());
                        }
                        json = JSON.parseObject(content);
                    } else {
                        logger.info("file not exist!");
                    }
    
    
    
                return json;
        }
           
    }

     3.pom 依赖

    <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                 <version>1.2.58</version>
     </dependency>
           <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
  • 相关阅读:
    自动安装rpm依赖
    goroutine上下文contxt语法
    goroutine 上下文用法
    Template Method 模式
    设计模式2--设计原则
    centos7关机自动进行远程服务器备份
    实用工具使用
    剑指offer python版 滑动窗口的最大值
    剑指offer python版 左旋转字符串
    剑指offer python版 翻转单词顺序
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/11108316.html
Copyright © 2011-2022 走看看