读取指定文件,转换为jsonObject
前言
最近的一个需求:
读取json文件,将文件内容转为jsonObject对象。
一、提前准备
在resources/static文件内创建jsonpath.json文件
jsonPath.json文件内容如下(一个jsonPath的例子):
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
二、使用ClassPathResource
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.io.InputStream;
public class JsonPathDemo {
public static JSONObject getJsonObject() {
InputStream defaultColumnInputStream;
JSONObject json = null;
try {
ClassPathResource defaultData = new ClassPathResource("static/jsonPath.json");
defaultColumnInputStream = defaultData.getInputStream();
json = JSONObject.parseObject(defaultColumnInputStream, JSONObject.class);
System.out.println(json);
System.out.println("--------------------");
} catch (IOException e) {
System.out.println("异常了");
}
return json;
}
public static void main(String[] args) {
getJsonObject();
}
}
三、输出结果
{
"store":{
"bicycle":{
"color":"red","price":19.95},"book":[{
"author":"Nigel Rees","price":8.95,"category":"reference","title":"Sayings of the Century"},{
"author":"Evelyn Waugh","price":12.99,"category":"fiction","title":"Sword of Honour"},{
"author":"Herman Melville","price":8.99,"isbn":"0-553-21311-3","category":"fiction","title":"Moby Dick"},{
"author":"J. R. R. Tolkien","price":22.99,"isbn":"0-395-19395-8","category":"fiction","title":"The Lord of the Rings"}]},"expensive":10}
--------------------
总结
读取文件方式千千万,随手记录一下