读取resources路径下的文件 并转为实体类 ---Spring项目

测试的时候,经常需要自己准备数据,通常会把自己准备的数据保存为json文件的放在项目资源包里。在java web项目中读取resource路径下的json文件并转为实体类有两种方式

这两种方式要注意,工具类实现不同,调用工具类传入的json文件路径的格式也不同。

Spring项目中读取resource路径下的json文件并转为实体类可以用ClassPathResource类来实现。参考Spring Boot 获取 java resources 下文件

1.新建工具类,接收json文件的路径和要转为的实体类,返回实体类或实体类的集合 

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;

import com.alibaba.fastjson.JSON;

public class Json2ObjectUtil {

	public static <T> T Json2Object(String jsonFilePath, Class<T> cls) throws IOException {

		// 读取json文件
		ClassPathResource resource = new ClassPathResource(jsonFilePath);

		// 获取文件流
		InputStream inputStream = resource.getInputStream();

		if (null == inputStream) {
			return null;
		}
		String jsontext = IOUtils.toString(inputStream, "utf8");

		// 转为实体类
		T object = JSON.parseObject(jsontext, cls);
		return object;
	}

	public static <T> List<T> Json2List(String jsonFilePath, Class<T> cls) throws IOException {

		ClassPathResource resource = new ClassPathResource(jsonFilePath);

		// 获取文件流
		InputStream inputStream = resource.getInputStream();

		if (null == inputStream) {
			return null;
		}
		String jsontext = IOUtils.toString(inputStream, "utf8");

		List<T> objectList = JSON.parseArray(jsontext, cls);
		return objectList;
	}
}

2.使用工具类的方法,把json文件转为实体类 

 student.json文件如下

{
	"studentId": "12",
	"studentName": "ABJ"
}

 studentList.json文件如下

[
	{
	"studentId": "12",
	"studentName": "ABJ"
    },
	{
	"studentId": "122",
	"studentName": "ABJR"
    }
]

 实现类如下

要非常注意filePath的格式 String filePath = "jsondata\\com\\demo\\service\\impl\\studentServiceImpl\\student.json";

import java.io.IOException;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import com.alibaba.fastjson.JSON;


@SpringBootTest
public class TestClass2 {

	@Test
	public void json2ObjectTest() throws IOException {

		// 在包下有student.json文件
		String filePath = "jsondata\\com\\demo\\service\\impl\\studentServiceImpl\\student.json";

		Student student = Json2ObjectUtil.Json2Object(filePath, Student.class);
		System.out.println("student=" + JSON.toJSONString(student));

	}

	@Test
	public void json2ListTest() throws IOException {

		// 在包下有studentList.json文件
		String filePath = "jsondata\\com\\demo\\service\\impl\\studentServiceImpl\\studentList.json";

		List<Student> students = Json2ObjectUtil.Json2List(filePath, Student.class);
		System.out.println("students=" + JSON.toJSONString(students));

	}

}

 

posted on 2020-07-22 15:42  dreamstar  阅读(574)  评论(0编辑  收藏  举报