第一种方式:读取本地的json文件
Resource resource;
resource = new ClassPathResource("static" + File.separator + "script" + File.separator + "pub"+ File.separator + "pub_close_browser_no_flow.json");
InputStream in = resource.getInputStream();
String jsonTxt = inputStream2String(in);
将流中的数据转为字段串
public String inputStream2String(InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
注:File.separator
/** * The system-dependent default name-separator character. This field is * initialized to contain the first character of the value of the system * property <code>file.separator</code>. On UNIX systems the value of this * field is <code>'/'</code>; on Microsoft Windows systems it is <code>'\\'</code>. * * @see java.lang.System#getProperty(java.lang.String) */
第二种方式:读取配置中心的json文件
String ip = ServerUtils.getServerIp(eurekaClient,configCenterServer);
String url = "http://" + ip + ":" + httpURLForScript;
String jsonTxt = HttpTemplateUtil.httpGet(url + "pub/pub_close_browser_no_flow.json");
jsonTxt = getScriptByParam(jsonTxt, explorerHandle);
ServerUtils是获取注册中心的工具类
public class ServerUtils {
public static String getServerIp(EurekaClient eurekaClient, String appName){
Application application = eurekaClient.getApplication(appName);
List<InstanceInfo> instanceInfoList = application.getInstances();
log.info("获取的服务的IP的地址:" + instanceInfoList.get(0).getIPAddr());
return instanceInfoList.get(0).getIPAddr();
}
}
最关键的一步,将字段串进行解析,解析出需要的集合
Type type = new TypeToken<List<T>>() {
}.getType();
List<T> tList = gson.fromJson(jsonTxt, type);