如何读取springboot项目中json文件

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值