版权声明:本文为「简简单单 Online zuozuo」原创文章,非商业用途欢迎转载,请保持署名,注明出处! Java 交流QQ 群:172083832 ,欢迎大家加入! https://blog.csdn.net/qq_15071263/article/details/85998713
Springboot 读取项目下的Json文件成对象
1、创建Json文件
{
"age": 30,
"comment": "哈哈哈",
"name": "小明",
"sex": 1
}
2、创建读取工具类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
/**
* @author Created by 谭健 on 2019/1/7. 星期一. 13:07.
* © All Rights Reserved.
*/
public class JsonUtils {
public static <T> T readJsonFromClassPath(String path, Type type) throws IOException {
ClassPathResource resource = new ClassPathResource(path);
if (resource.exists()) {
return JSON.parseObject(resource.getInputStream(), StandardCharsets.UTF_8, type,
// 自动关闭流
Feature.AutoCloseSource,
// 允许注释
Feature.AllowComment,
// 允许单引号
Feature.AllowSingleQuotes,
// 使用 Big decimal
Feature.UseBigDecimal);
} else {
throw new IOException();
}
}
}
3、读取
// 读取项目路径下的文件 json/person.json
Person person = JsonUtils.readJsonFromClassPath("json/person.json", Person.class);
System.out.println(person.toString());
4、输出
ReadJson.Person(name=小明, age=30, sex=1, comment=哈哈哈)