Springboot 讀取專案下的Json檔案成物件
阿新 • • 發佈:2019-01-07
文章目錄
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=哈哈哈)