spring boot里读取json文件是一个常见操作,之前在本地idea运行时候读取json文件没有任何问题,但是打包发布后运行会读取不到,解决方法:
-
要将json文件放到static目录下
-
读取文件要用 ClassPathResource 和 fastJson
-
具体操作代码:
调用方法:
JSONObject jsonData = JSON.parseObject(BaseUtil.readJsonFileNew("static/json/ZKManageCode.json"));
readJsonNew方法:
public static String readJsonFileNew(String jsonPath) {
String jsonStr = "";
try {
ClassPathResource classPathResource = new ClassPathResource(jsonPath);
InputStream inputStream = classPathResource.getInputStream();
Reader reader = new InputStreamReader(inputStream, "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
得到jsonData后就可以得到里边的json对象和对应的键值:
JSONObject jsonObj = JSON.parseObject(jsonData.getString("obj"));//获取obj 对象
String value = jsonObj.getString(dto.getVerify_type());//obj对象里,通过key获取value
大功告成!!!