后台开发的时候,有时候需要用json做一些假数据或者做一些配置。这个时候,怎么读取接送数据?我查了一些资料,最后我这样解决了。
json数据
{
"resultCode":200,
"code":200,
"data":{
"versionName":"1.2.0",
"versionInfo":[
"1.新版本信息......",
"2.新版本信息......",
"3.XUtil.getInstance().postJson(Urls.getWLJYList()......新版本信息新版本信息"
]
}
}
json文件的工具类
package com.wdcloud.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdcloud.app.AppInterfaceMainpage;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.IOException;
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;
}
}
简单的使用
//获取新版本的数据
@RequestMapping(value = {"/getNewVersionInfo"}, method = {RequestMethod.POST})
@ResponseBody
public Object getNewVersionInfo(HttpServletRequest request, HttpServletResponse response) {
logger.info("/getNewVersionInfo");
return JsonResourceUtils.getJsonObjFromResource("/json/app_version_info.json");
}