JAVA-JSON配置文件读取工具类

有些功能需要再配置文件里通过JSON形式进行配置。下面是一个JSON文件解析工具,方便解析JSON内容。

public class FileFormatUtil {
    protected static final Logger LOGGER = LoggerFactory.getLogger(FileFormatUtil.class);

    private static final String PATH = "classpath:conf/file-format.json";
    private static volatile Map<String, JSONObject> fileFormatMap = null;

    static {
        try {
            fileFormatMap = new HashMap<>();
            File file = ResourceUtils.getFile(PATH);
            String jsonString = FileUtils.readFileToString(file, "UTF-8");

            JSONArray jsonArray = new JSONArray(jsonString);
            jsonArray.stream().forEach( env -> {
                JSONObject jsonObject = (JSONObject) env;
                fileFormatMap.put(String.valueOf(jsonObject.get("id")), jsonObject);
            });
        }catch (Exception e) {
            LOGGER.error("file-format.json失败,", e);
        }
    }

    /***
     * 获取正则表达式
     * @param id
     * @return
     * @throws IOException
     */
    public static String getRegularExpression(String id) {
        JSONObject jsonObject = fileFormatMap.get(String.valueOf(id));
        return jsonObject == null? null : jsonObject.getStr("regularExpression");
    }


    public static Map<String, JSONObject> getAllFormat() {
        return fileFormatMap;
    }

}