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>

 

posted @ 2019-06-29 23:43  江期玉  阅读(806)  评论(0编辑  收藏  举报