读取resources路径下的文件 并转为实体类 ---java 方式

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

工具类中读取文件 用Spring方式  读取resources路径下的文件 并转为实体类 ---Spring项目
工具类中读取文件 用java方式  读取resources路径下的文件 并转为实体类 ---java 方式

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

参考 fastjson 的使用总结

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

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
 
import org.apache.commons.io.IOUtils;
 
import com.alibaba.fastjson.JSON;
 
public class Json2ObjectUtil {
 
	public static <T> T Json2Object(String jsonFilePath, Class<T> cls) throws IOException {

		//读取josn文件 获取文件流
		InputStream inputStream = Json2ObjectUtil.class.getResourceAsStream(jsonFilePath);
 
		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 {
 
 	    //读取josn文件 获取文件流
		InputStream inputStream = Json2ObjectUtil.class.getResourceAsStream(jsonFilePath);
		
		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 fileString = "/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 fileString = "/jsondata/com/demo/service/impl/studentServiceImpl/student.json";
		Student student = JsonObjectUtil.parseObjectFromJsonFile(fileString, 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 = JsonObjectUtil.parseArrayFromJsonFile(filePath, Student.class);
		System.out.println("students=" + JSON.toJSONString(students));
 
	}
 
}

 

posted on 2020-07-22 16:18  dreamstar  阅读(520)  评论(0编辑  收藏  举报