假设一个json文件是这样子的,
[ {"id": "uploadDlg","by": "xpath","expr": "//div[text()=‘Click this button or drag files here to import the data‘]","description": "upload files Dialog"}, {"id": "upload","by": "xpath","expr": "//label[@role=‘button‘]/span/input","description": "upload files"} ]
数组对象在转换时,会变成一个json的treemap,所以必须一条一条拿出来加到list中。
用如下方法转换:
public static synchronized <T> List<T> loadJson(InputStream inputStream, Class<T> clazz) { List<T> list=new ArrayList<>(); try { Gson gson=new Gson(); JsonArray jsonArray= JsonParser.parseReader(new InputStreamReader(inputStream)).getAsJsonArray(); for(JsonElement jsonElement:jsonArray){ list.add(gson.fromJson(jsonElement,clazz)); } } catch (Exception e) { BuildStatus.getInstance().recordError(); logger.error(e.getMessage(), e); } return list; }
当然当转换的对象可识别的时候,用如下
private static synchronized List<ARPCISetting> loadJson(String file) { try { java.lang.reflect.Type type = new TypeToken<List<ARPCISetting>>() { }.getType(); if ((System.getProperty("file.separator").equals("/") && !file.startsWith("/")) || (System.getProperty("file.separator").equals("\\") && !file.contains(":"))) { if (file.contains("/") || file.contains("\\")) { file = Helper.reviseFilePath(Helper.getParentPath(System.getProperty("user.dir")) + file); } else { file = Helper.reviseFilePath(System.getProperty("user.dir") + "/" + file); } } File fileHd = new File(file); if (fileHd.exists()) { return new Gson().fromJson(new FileReader(fileHd), type); } return new ArrayList<>(); } catch (Exception e) { BuildStatus.getInstance().recordError(); logger.error(e.getMessage(), e); return new ArrayList<>(); } }
原文:https://www.cnblogs.com/qiyanse/p/14543048.html