json 文件打读取

本文详细介绍了一种在Java环境中读取和解析JSON文件的方法,包括如何获取项目中JSON文件的路径,使用fastjson库解析JSON数据,并将其转换为JSONObject。此外,还介绍了如何在代码中处理文件不存在的情况及异常捕获。

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>

 

转载于:https://www.cnblogs.com/jiangfeilong/p/11108316.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值