Esempio n. 1
0
        // ---------------------------------------
        // ------ 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);
        }
Esempio n. 2
0
        static void testRootNotAnObjectException()
        {
            JSONParse parser = new JSONParse(SAMPLE3);

            try
            {
                parser.asMap();
                System.assert(false, "Root node is not an object, should have seen an exception about that.");
            }
            catch (JSONParse.NotAnObjectException e)
            {
                System.assert(e.getMessage().startsWith("The wrapped value is not a JSON object:"));
            }
        }