java读取json文件

一、假设json结构如下:

{
  "Settings": [
    {
      "name": "系统标识码",
      "key": "API_SYS_CODE",
      "params": [ "SYS_CODE" ],
      "disabled": "false",
      "edited": "false",
      "type": "string",
      "maxLength": "50",
      "value": ""
    },
    {
      "name": "备案地区",
      "key": "API_BEIANDIQU_CODE",
      "params": [ "BEIANDIQU_CODE" ],
      "disabled": "false",
      "edited": "false",
      "type": "string",
      "maxLength": "50",
      "value": ""
    }
  ]
}

 二、读取json

package com.sxsoft.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.*;

/**
 * @program: sxsoft_operation_admin
 * @ClassName JsonFileUtil
 * @description:
 * @author: 黄涛
 * @create: 2023-03-10 17:27
 * @Version 1.0
 **/
public class JsonFileUtil {

    /**
     * 读取json文件
     * @param filePath
     * @return
     */
    public static JSONArray readJsonFile(String filePath) {

        FileReader fileReader = null;
        Reader reader = null;
        try {
            File jsonFile = new File(filePath);
            fileReader = new FileReader(jsonFile);
            reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            String jsonStr = sb.toString();
            JSONObject jobj = JSON.parseObject(jsonStr);
            JSONArray settings = jobj.getJSONArray("Settings");//构建JSONArray数组
            return settings;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                if(fileReader!=null){
                    fileReader.close();
                }
                if(reader!=null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}

三、使用,每次都读json文件似乎不太好,可以考虑将数据缓存到内存或者redis中。

package com.sxsoft.utils;

import com.alibaba.fastjson.JSONArray;
import com.sxsoft.config.CacheManageConfig;
/**
 * @program: sxsoft_operation_admin
 * @ClassName CacheClass
 * @description:内存缓存,注意key的使用,不能重复
 * @author: 黄涛
 * @create: 2023-03-10 17:59
 * @Version 1.0
 **/
public class LocalCacheUtil {

    /**
     *缓存本地json文件数据
     * @param filePath
     * @param key
     * @return
     */
   public static JSONArray getJsonFile(String filePath,String key){
       if(CacheManageConfig.checkCacheName(key)){
           JSONArray objects = CacheManageConfig.getCache(key);
           return objects;
       }else {
           JSONArray nowData = JsonFileUtil.readJsonFile(filePath);
           CacheManageConfig.putCache(key,nowData);
           return nowData;
       }

   }



}
package com.sxsoft.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.istrong.ec.common.utils.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Iterator;

/**
 * @program: sxsoft_operation_admin
 * @ClassName CacheManager
 * @description:本地缓存管理
 * @author: 黄涛
 * @create: 2023-03-13 08:33
 * @Version 1.0
 **/
@Configuration
@EnableScheduling
public class CacheManageConfig {

    /**
     * 预缓存数据集
     */
    private final static ConcurrentHashMap CACHES;

    /**
     * 单个预缓存生效时间
     */
    public static final long CACHE_HOLD_TIME = 1 * 60 * 60 * 1000L;

    /**
     * 缓存时效时间key标识
     */
    public static final String CACHE_HOLD_TIME_KEY = "hold_time";

    static {
        CACHES = new ConcurrentHashMap();
    }

    /**
     * 添加缓存信息(默认缓存1小时)
     *
     * @param cacheName
     * @param objValue
     */
    public static void putCache(String cacheName, Object objValue) {
        putCache(cacheName, objValue, CACHE_HOLD_TIME);
    }

    /**
     * 存放一个缓存对象,保存时间为holdTime
     *
     * @param cacheName
     * @param objValue
     * @param holdTime
     */
    public static void putCache(String cacheName, Object objValue, long holdTime) {
        if (checkCacheName(cacheName)) {
            return;
        }
        CACHES.put(cacheName, objValue);
        CACHES.put(cacheName + CACHE_HOLD_TIME_KEY, System.currentTimeMillis() + holdTime);
    }

    /**
     * 获取缓存数据
     *
     * @param cacheName
     * @return value
     */
    public static <T> T getCache(String cacheName) {
        if (checkCacheName(cacheName)) {
            return (T) CACHES.get(cacheName);
        }
        return null;
    }

    /**
     * 检查缓存对象是否存在,
     * 若不存在,则返回false
     * 若存在,检查其是否已过有效期,如果已经过了生效期则删除该缓存并返回false
     *
     * @param cacheName
     * @return
     */
    public static boolean checkCacheName(String cacheName) {

        Long cacheHoldTime = (Long) CACHES.get(cacheName + CACHE_HOLD_TIME_KEY);
        if (cacheHoldTime == null || cacheHoldTime == 0L) {
            return false;
        }
        if (cacheHoldTime < System.currentTimeMillis()) {
            removeCache(cacheName);
            return false;
        }
        return true;
    }


    /**
     * 清除缓存
     */
    public static void clearCache() {
        CACHES.clear();
    }

    /**
     * 根据key删除信息
     *
     * @param cacheName
     */
    public static void removeCache(String cacheName) {

        CACHES.remove(cacheName);
        CACHES.remove(cacheName + CACHE_HOLD_TIME_KEY);
    }

    /**
     * 定时删除任务
     */
    @Scheduled(cron = "0 */10 * * * ?")
    private void removeJob() {
        if (CACHES.size() <= 0) {
            return;
        }
        Iterator<Map.Entry<String, Object>> iterator = CACHES.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            String key = next.getKey();
            if (key.endsWith(CACHE_HOLD_TIME_KEY)) {
                Long value = (Long) next.getValue();
                if (value < System.currentTimeMillis()) {
                    CACHES.remove(key);
                    CACHES.remove(StringUtils.removeEnd(key, CACHE_HOLD_TIME_KEY));
                }
            }
        }
    }

}
String basePath = System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径 
JSONArray array = LocalCacheUtil.getJsonFile(basePath + "\\StaticResource\\projectField_1.json","projectField_1_key");

posted on 2023-03-13 13:48  五官一体即忢  阅读(910)  评论(0编辑  收藏  举报

导航