SringBoot解析json文件
👇下面连接是我解析JSON文件时参考的资料,可以正常解析,但打包后接口报错,无法找到正确的文件路径。
版权声明:本文为CSDN博主「肥肥技术宅」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_71777195/article/details/127050596
👇这是我找到一些资料后做出的解决方案,希望能帮到你。
1、pom文件中引入
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
2、在resource/static目录下创建json文件
3、编写readJsonFileNew()静态方法
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;
}
}
4、调用readJsonFileNew()方法,将文件路径传入
public AjaxResult getBaseInfo() {
logger.info("进入站点基本信息接口");
Map<String, Object> res = new HashMap<>();
JSONArray jsonData = JSON.parseArray(readJsonFileNew("static/workstation.json"));
res.put("infoList", jsonData);
return AjaxResult.success(res);
}
5、大功告成!!!✌