找一個工具讀取json檔案,網上好多,找了一個測試了下,記錄下來
1. 要放入讀取io的依賴包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2. 建立一個json格式的檔案放入resources下
檔案内容:
3. 建立工具類 JsonResourceUtils
package com.***.***.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import java.io.File;
import java.net.URL;
public class JsonResourceUtils {
private static Logger logger = Logger.getLogger(JsonResourceUtils.class);
private JsonResourceUtils() {
}
//filename 為檔案名字 如 “/json/app_version_info.json”
public static JSONObject getJsonObjFromResource(String filename) {
JSONObject json = null;
if (!filename.contains(".json")) {
filename += ".json";
}
try {
URL url = JsonResourceUtils.class.getResource(filename);
String path = url.getPath();
File file = new File(path);
if (file.exists()) {
String content = FileUtils.readFileToString(file, "UTF-8");
json = JSON.parseObject(content);
} else {
logger.info("file not exist!");
}
} catch (Exception e) {
e.printStackTrace();
logger.info("readFileToString" + e.getMessage());
}
return json;
}
}
4.控制層讀取
@RequestMapping(value = {"/getJsonFile"}, method = {RequestMethod.POST})
//@ResponseBody (控制層已使用@RestController)
public Object getJsonFile(HttpServletRequest request, HttpServletResponse response){
return JsonResourceUtils.getJsonObjFromResource("/aaa.json");
}
5. 運作結果