注意:这两种方式打成jar包很有可能读取不到数据。解决方法,请参考: Springboot下jar如何读取静态配置JSON文件
方式一:
private void parseJson(){
File jsonFile = ResourceUtils.getFile("classpath:serviceConfig.json");
String json = FileUtils.readFileToString(jsonFile);
JSONArray jsonArray = JSON.parseArray(json);
for (Object obj : jsonArray) {
JSONObject jobj = (JSONObject) obj;
String iso = jobj.getString("***");
}
}
方式二:
@Value("classpath:serviceConfig.json")
private Resource resource;
private void parseJson(){
File file = areaRes.getFile();
String jsonData = this.jsonFileReader(file);
JSONObject jsonObject = JSONObject.parseObject(jsonData);
.....
}
private String jsonFileReader(File file){
Scanner scanner = null;
StringBuilder buffer = new StringBuilder();
try {
scanner = new Scanner(file, "utf-8");
while (scanner.hasNextLine()) {
buffer.append(scanner.nextLine());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
return buffer.toString();
}