java jackson 读写修改json文件

json数据格式:
// {"test":[{"volume":234,"driver":[{"ip":"192.168.1.1"},{"ip":"192.168.1.2"},{"ip":"192.168.1.3"}]},{"volume":234123,"driver":[{"ip":"192.168.1.1"},{"ip":"192.168.1.2"},{"ip":"192.168.1.3"}]}]}
//读
synchronized public static boolean existInMultiPathConfigFile(long volumeId) { try { ObjectMapper objMap = new ObjectMapper(); System.out.println("array size is 111111111111111111"); JsonNode root = objMap.readTree(new File("/home/test/multipaths.conf")); System.out.println("array size is 2222222222222222222222"); JsonNode node = root.path("test"); System.out.println("array size is " + node.size()); for (int i = 0; i < node.size(); i++) { Long volume = node.path(i).path("volume").asLong(); if (volume.equals(volumeId)) { System.out.println("exist connection in multipaths.conf."); return true; } } } catch (Exception ex) { System.out.println("error to read config file."); return false; } System.out.println("nonexist@@@@@@@@@@@@@@@@@@@@."); return false; } //写 synchronized public static boolean writeMultiPathConfigFile(long volumeId, List<String> ips) { try { ObjectMapper objMap = new ObjectMapper(); JsonNode root = objMap.readTree(new File("/home/test/multipaths.conf")); ArrayNode node = (ArrayNode)root.path("test"); ObjectNode newNode = objMap.createObjectNode(); newNode.put("volume", volumeId); ArrayNode ipArray = objMap.createArrayNode(); for (String ip : ips) { ObjectNode ipNode = objMap.createObjectNode(); ipNode.put("ip", ip); ipArray.add(ipNode); } newNode.put("driver", ipArray); node.add(newNode); OutputStream outputStream = new FileOutputStream(new File("/home/test/multipaths.conf")); objMap.writeValue(outputStream, root); } catch (Exception ex) { System.out.println("error to read config file."); return true; } return false; }
//删除 synchronized public static boolean eraseMultiPathConfigFile(long volumeId) { try { ObjectMapper objMap = new ObjectMapper(); JsonNode root = objMap.readTree(new File("/home/test/multipaths.conf")); JsonNode node = root.path("test"); Iterator<JsonNode> iter = node.iterator(); while (iter.hasNext()) { JsonNode next = iter.next(); System.out.println("erase the match line." + next.get("volume")); if (next.get("volume").asLong() == volumeId) { System.out.println("erase the match line.******************"); iter.remove(); } } OutputStream outputStream = new FileOutputStream(new File("/home/test/multipaths.conf")); objMap.writeValue(outputStream, root); } catch (Exception ex) { System.out.println("error to read config file."); return true; } return false; }