前言
记录下SpringBoot
读取JSON
文件的方式
具体实现
JsonUtil.java
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class JsonUtil {
/**
* 读取JSON文件转换为字符串
* @param filePath
* @return
*/
public static String readJsonFile(String filePath) {
String jsonStr = "";
try {
File jsonFile = new File(filePath);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
转换例子
- 借助
fastjson
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.48</version>
</dependency>
- 对象形式读取转换
String jsonStr = JsonUtil.readJsonFile("src/main/resources/json/xxx.json");
JSONObject result = JSONObject.parseObject(jsonStr);
- 数组形式读取转换
String jsonStr = JsonUtil.readJsonFile("src/main/resources/json/xxx.json");
JSONArray result = JSONObject.parseArray(jsonStr);