Spring项目中加载resources资源文件并转换为Java对象
在开发与测试过程中,常需使用预定义的测试数据。将JSON格式的数据文件存放在项目的resources目录下是一种常见做法。在Spring或Spring Boot项目中,可以通过Spring提供的资源访问机制便捷地读取这些文件,并将其反序列化为Java实体对象。
核心实现依赖于ClassPathResource类,它允许从类路径中加载资源文件。结合FastJSON等JSON处理库,可轻松完成文件内容到对象的转换。
工具类实现:从类路径读取JSON并转为对象
以下是一个通用工具类,支持将resources目录下的JSON文件解析为单个对象或对象列表:
import org.springframework.core.io.ClassPathResource;
import com.alibaba.fastjson.JSON;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class ResourceJsonParser {
/**
* 读取类路径下的JSON文件,转换为指定类型的Java对象
*
* @param location 资源文件路径(相对于resources目录)
* @param clazz 目标类类型
* @return 解析后的对象,若文件不存在则返回null
*/
public static <T> T loadAsObject(String location, Class<T> clazz) throws Exception {
ClassPathResource resource = new ClassPathResource(location);
try (InputStream is = resource.getInputStream()) {
String content = new String(is.readAllBytes(), StandardCharsets.UTF_8);
return JSON.parseObject(content, clazz);
}
}
/**
* 读取类路径下的JSON数组文件,转换为对象列表
*
* @param location 资源文件路径
* @param elementClass 列表元素类型
* @return 解析后的对象列表
*/
public static <T> List<T> loadAsList(String location, Class<T> elementClass) throws Exception {
ClassPathResource resource = new ClassPathResource(location);
try (InputStream is = resource.getInputStream()) {
String content = new String(is.readAllBytes(), StandardCharsets.UTF_8);
return JSON.parseArray(content, elementClass);
}
}
}
测试数据文件示例
student.json —— 单个学生信息:
{
"studentId": "12",
"studentName": "ABJ"
}
studentList.json —— 学生信息列表:
[
{
"studentId": "12",
"studentName": "ABJ"
},
{
"studentId": "122",
"studentName": "ABJR"
}
]
单元测试调用示例
假设上述JSON文件位于 src/main/resources/jsondata/com/demo/service/impl/studentServiceImpl/ 路径下,测试代码如下:
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class ResourceJsonParserTest {
@Test
public void shouldLoadStudentObject() throws Exception {
String path = "jsondata/com/demo/service/impl/studentServiceImpl/student.json";
Student student = ResourceJsonParser.loadAsObject(path, Student.class);
System.out.println("Loaded student: " + student);
}
@Test
public void shouldLoadStudentList() throws Exception {
String path = "jsondata/com/demo/service/impl/studentServiceImpl/studentList.json";
List<Student> students = ResourceJsonParser.loadAsList(path, Student.class);
System.out.println("Loaded students: " + students.size());
}
}
注意传入的路径应使用正斜杠/分隔,这是类路径查找的标准格式,无需转义反斜杠。该方式适用于Spring环境,能正确处理打包后的jar内资源访问。