// --------------------------------------- // ------ Interactions ------------------- // --------------------------------------- /** * Drill into a nested structure to get to some subtree in the document. We allow the path to include a mix * of array notation and string keys. * * @param path * * @return A new JSONParse wrapper that wraps the targeted subtree. * @throws NotAnArrayException if we try to apply an array notation to a node that isn't an array * @throws NotAnObjectException if we try to apply a map key to a node that isn't an object * @throws MissingKeyException if part of the path can't be resolved because there is no match on that key */ public JSONParse get(string path) { JSONParse currentNode = this; // we start with ourselves and drill deeper // drill down through the nested structure foreach (string key in path.split("\\.")) { // check to see if we are going to parse this key as a reference to an array item Matcher arrayMatcher = ARRAY_NOTATION.matcher(key); if (arrayMatcher.matches()) { int index = Integer.valueOf(arrayMatcher.group(1)); currentNode = currentNode.asList().get(index); } else { // otherwise, treat this key as a normal map key Map <string, JSONParse> wrappedMap = currentNode.asMap(); if (!wrappedMap.containsKey(key)) { throw new MissingKeyException("No match found for <" + key + ">: " + wrappedMap.keySet()); } currentNode = wrappedMap.get(key); } } return(currentNode); }
static void testAsList() { JSONParse parser = new JSONParse(SAMPLE3); System.assertEquals(false, parser.isObject()); System.assertEquals(true, parser.isArray()); List <JSONParse> items = parser.asList(); System.assertEquals(5, items.size()); System.assertEquals("*****@*****.**", items[0].get("init-param.configGlossary:adminEmail").getValue()); System.assertEquals(true, items[1].get("init-param").isObject()); System.assertEquals("cofaxEmail", items[1].get("servlet-name").getStringValue()); }
static void testRootNotAnArrayException() { JSONParse parser = new JSONParse(SAMPLE2); try { parser.asList(); System.assert(false, "Root node is not an array, should have seen an exception about that."); } catch (JSONParse.NotAnArrayException e) { System.assert(e.getMessage().startsWith("The wrapped value is not a JSON array:")); } }