一、前言
在springboot项目我们常常需要获取配置文件,包括但不限于YML、XML、Properties、JSON等类型文件;Properties和YML一般作为项目的主要配置文件,通过注解@Value即可读取;那么JSON文件应该如何读取呢?
二、实现读取JSON文件(示例JSON为对象集合)
2.1 开发环境路径

2.2 打包环境路径

2.3 直接上详细代码
private final ResourceLoader resourceLoader;
@Autowired
public SxxxxxService(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
// 读取 JSON 文件内容到字符串
String jsonString = null;
Resource resource = resourceLoader.getResource("classpath:fxxxxx.json");
try {
jsonString = new String(toByteArray(resource.getInputStream()), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
JSONArray result = JSONObject.parseArray(jsonString);
/**
* 输入流转byte字节数组
* @param input
* @return
* @throws IOException
*/
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try(InputStream in = input){
IOUtils.copy(in, output);
}
return output.toByteArray();
}
2.4 注意Resource的引用包为org.springframework.core.io.Resource
本文介绍了如何在SpringBoot项目中使用ResourceLoader读取类路径下的JSON文件,提供开发环境和打包环境路径示例,以及处理异常的代码片段。

1873

被折叠的 条评论
为什么被折叠?



