• 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>
  • 相关阅读:
    BIM软件小技巧:Revit2014所有快捷键汇总表格
    ubuntu下启动、关闭tomcat,查看tomcat运行日志
    Ubuntu14.04下安装tomcat
    ubuntu eclipse 不能新建javaweb项目解决方案
    在Ubuntu 14.04中安装最新版Eclipse
    Ubuntu14.04下jdk的安装
    Ubuntu14.04安装JDK与配置环境变量
    ubuntu14.04完全卸载mysql
    Ubuntu14.04下MySQL的安装
    ubuntu14.04切换root用户
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/11108316.html
Copyright © 2020-2023  润新知