首页 前端知识 如何读取springboot项目中json文件

如何读取springboot项目中json文件

2024-09-12 23:09:26 前端知识 前端哥 598 714 我要收藏

一、前言
在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

转载请注明出处或者链接地址:https://www.qianduange.cn//article/18239.html
标签
评论
发布的文章

关于HTML的知识

2024-09-18 23:09:36

js简单实现轮播图效果

2024-09-18 23:09:36

CSS3美化网页元素

2024-09-18 23:09:27

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!