From 834c4465c095692f164accb8fcbb56bf5ae581e0 Mon Sep 17 00:00:00 2001 From: kalle Date: Tue, 1 Feb 2011 23:21:04 +0100 Subject: [PATCH] testing JSONPath concepts --- .../com/jayway/jsonassert/JsonAssert.java | 10 +- .../java/com/jayway/jsonassert/JsonPath.java | 2 +- .../jayway/jsonassert/impl/JsonPathImpl.java | 111 ++++++- .../jsonassert/impl/JsonReaderImpl.java | 277 ---------------- .../java/com/jayway/jsonassert/impl/Path.java | 10 + .../jayway/jsonassert/impl/PathFragment.java | 7 + .../jayway/jsonassert/JsonPathSpecTest.java | 105 ++++++ .../com/jayway/jsonassert/JsonReaderTest.java | 300 ------------------ 8 files changed, 232 insertions(+), 590 deletions(-) delete mode 100644 json-assert/src/main/java/com/jayway/jsonassert/impl/JsonReaderImpl.java create mode 100644 json-assert/src/test/java/com/jayway/jsonassert/JsonPathSpecTest.java delete mode 100644 json-assert/src/test/java/com/jayway/jsonassert/JsonReaderTest.java diff --git a/json-assert/src/main/java/com/jayway/jsonassert/JsonAssert.java b/json-assert/src/main/java/com/jayway/jsonassert/JsonAssert.java index 2b2a124d..a171378d 100644 --- a/json-assert/src/main/java/com/jayway/jsonassert/JsonAssert.java +++ b/json-assert/src/main/java/com/jayway/jsonassert/JsonAssert.java @@ -1,7 +1,7 @@ package com.jayway.jsonassert; import com.jayway.jsonassert.impl.JsonAsserterImpl; -import com.jayway.jsonassert.impl.JsonReaderImpl; +import com.jayway.jsonassert.impl.JsonPathImpl; import java.io.IOException; import java.io.Reader; @@ -22,7 +22,7 @@ public class JsonAssert { * @throws ParseException */ public static JsonPath parse(String jsonDoc) throws ParseException { - return JsonReaderImpl.parse(jsonDoc); + return JsonPathImpl.parse(jsonDoc); } /** @@ -48,7 +48,7 @@ public class JsonAssert { public static JsonPath parse(Reader reader, boolean closeReader) throws ParseException, IOException { JsonPath jsonReader = null; try { - jsonReader = JsonReaderImpl.parse(reader); + jsonReader = JsonPathImpl.parse(reader); } finally { if(closeReader){ try { @@ -67,7 +67,7 @@ public class JsonAssert { * @throws ParseException when the given JSON could not be parsed */ public static JsonAsserter with(String json) throws ParseException { - return new JsonAsserterImpl(JsonReaderImpl.parse(json)); + return new JsonAsserterImpl(JsonPathImpl.parse(json)); } /** @@ -78,7 +78,7 @@ public class JsonAssert { * @throws ParseException when the given JSON could not be parsed */ public static JsonAsserter with(Reader reader) throws ParseException, IOException { - return new JsonAsserterImpl(JsonReaderImpl.parse(reader)); + return new JsonAsserterImpl(JsonPathImpl.parse(reader)); } } diff --git a/json-assert/src/main/java/com/jayway/jsonassert/JsonPath.java b/json-assert/src/main/java/com/jayway/jsonassert/JsonPath.java index 35e014bf..aa189531 100644 --- a/json-assert/src/main/java/com/jayway/jsonassert/JsonPath.java +++ b/json-assert/src/main/java/com/jayway/jsonassert/JsonPath.java @@ -71,5 +71,5 @@ public interface JsonPath { * @param path * @return */ - Map getMap(String path); + Map getMap(String path); } diff --git a/json-assert/src/main/java/com/jayway/jsonassert/impl/JsonPathImpl.java b/json-assert/src/main/java/com/jayway/jsonassert/impl/JsonPathImpl.java index 48afbf62..8eeaa0ab 100644 --- a/json-assert/src/main/java/com/jayway/jsonassert/impl/JsonPathImpl.java +++ b/json-assert/src/main/java/com/jayway/jsonassert/impl/JsonPathImpl.java @@ -16,7 +16,7 @@ import java.util.Map; * User: kalle stenflo * Date: 2/1/11 * Time: 8:45 AM - * + *

* http://goessner.net/articles/JsonPath/ */ public class JsonPathImpl implements JsonPath { @@ -43,28 +43,121 @@ public class JsonPathImpl implements JsonPath { } } + public static T jsonPath(Object model, String path) { + JsonPathImpl p = new JsonPathImpl(model); + + return (T) p.get(path); + } + + public JsonPathImpl(Object model) { this.model = model; } + + private void searchFragment(Object visit, PathFragment fragment, PathFragment filter, ReaderContext ctx) { + ctx.split(); + if (isDocument(visit)) { + Map document = toDocument(visit); + + for (Map.Entry entry : document.entrySet()) { + + if (entry.getKey().equals(fragment.value())) { + + if (isArray(entry.getValue()) && filter.isArrayIndex()) { + JSONArray array = toArray(entry.getValue()); + for (int i = 0; i < array.size(); i++) { + boolean include = true; + + if (filter.isArrayIndex() && filter.getArrayIndex() != i) { + include = false; + } + + if (include) { + ctx.addResult(array.get(i)); + } + } + } else { + ctx.addResult(entry.getValue()); + } + } + + if (isContainer(entry.getValue())) { + searchFragment(entry.getValue(), fragment, filter, ctx); + } + } + } else { + JSONArray array = toArray(visit); + + for (Object arrayItem : array) { + if (isContainer(arrayItem)) { + searchFragment(arrayItem, fragment, filter, ctx); + } + } + + } + } + + private void extractFragment(Object visit, PathFragment fragment, PathFragment criteria, ReaderContext ctx) { + ctx.split(); + if (isDocument(visit)) { + Map document = toDocument(visit); + + for (Map.Entry entry : document.entrySet()) { + + if (entry.getKey().equals(fragment.value()) || fragment.isWildcard()) { + ctx.addResult(entry.getValue()); + } + + if (!fragment.isWildcard() && isContainer(entry.getValue())) { + extractFragment(entry.getValue(), fragment, criteria, ctx); + } + } + } else { + JSONArray array = toArray(visit); + + for (Object arrayItem : array) { + if (isContainer(arrayItem)) { + extractFragment(arrayItem, fragment, criteria, ctx); + } + } + } + } + private void read(Object root, Path path, ReaderContext ctx, boolean strict) { if (!path.hasMoreFragments()) { ctx.addResult(root); return; } + if (path.peek().isWildcard()) { + PathFragment wildcard = path.poll(); + PathFragment extract = path.hasMoreFragments() ? path.poll() : wildcard; + PathFragment filter = path.hasMoreFragments() ? path.poll() : wildcard; + searchFragment(root, extract, filter, ctx); + return; + } + + if (isDocument(root)) { PathFragment fragment = path.poll(); - if(strict && !toDocument(root).containsKey(fragment.value())){ + if (strict && !toDocument(root).containsKey(fragment.value())) { throw new InvalidPathException(); } - Object extracted = toDocument(root).get(fragment.value()); + Object current = toDocument(root).get(fragment.value()); - if (fragment.isLeaf()) { - ctx.addResult(extracted); + if (path.hasMoreFragments() && path.peek().isWildcard()) { + PathFragment wildcard = path.poll(); + PathFragment extract = path.hasMoreFragments() ? path.poll() : wildcard; + PathFragment filter = path.hasMoreFragments() ? path.poll() : wildcard; + extractFragment(current, extract, filter, ctx); + return; + } + else if (fragment.isLeaf()) { + ctx.addResult(current); } else { - read(extracted, path.clone(), ctx, strict); + read(current, path.clone(), ctx, strict); } } else { PathFragment fragment = path.poll(); @@ -163,10 +256,14 @@ public class JsonPathImpl implements JsonPath { return get(path); } - public Map getMap(String path) { + public Map getMap(String path) { return get(path); } + private boolean isContainer(Object obj) { + return (isArray(obj) || isDocument(obj)); + } + private boolean isArray(Object obj) { return (obj instanceof JSONArray); } diff --git a/json-assert/src/main/java/com/jayway/jsonassert/impl/JsonReaderImpl.java b/json-assert/src/main/java/com/jayway/jsonassert/impl/JsonReaderImpl.java deleted file mode 100644 index d61e51a7..00000000 --- a/json-assert/src/main/java/com/jayway/jsonassert/impl/JsonReaderImpl.java +++ /dev/null @@ -1,277 +0,0 @@ -package com.jayway.jsonassert.impl; - -import com.jayway.jsonassert.InvalidPathException; -import com.jayway.jsonassert.JsonPath; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.io.Reader; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import static org.apache.commons.lang.Validate.notNull; - -/** - * User: kalle stenflo - * Date: 1/20/11 - * Time: 4:27 PM - */ -public class JsonReaderImpl implements JsonPath { - - - private static final JSONParser JSON_PARSER = new JSONParser(); - - private Object root; - private String currentPath; - - - public static synchronized JsonPath parse(Reader reader) throws java.text.ParseException, IOException { - try { - return new JsonReaderImpl(JSON_PARSER.parse(reader)); - } catch (IOException e) { - throw e; - } catch (ParseException e) { - throw new java.text.ParseException(e.getMessage(), e.getPosition()); - } - } - - public static synchronized JsonPath parse(String jsonDoc) throws java.text.ParseException { - try { - return new JsonReaderImpl(JSON_PARSER.parse(jsonDoc)); - } catch (ParseException e) { - throw new java.text.ParseException(e.getMessage(), e.getPosition()); - } - } - - private JsonReaderImpl(Object root) { - notNull(root, "root object can not be null"); - this.root = root; - } - - /** - * {@inheritDoc} - */ - public JsonPath getReader(String path) { - - Object jsonObject = get(path); - - if (!isArray(jsonObject) && !isDocument(jsonObject)) { - throw new InvalidPathException("path points to a leaf that is not a JSON document or Array"); - } - - return new JsonReaderImpl(jsonObject); - } - - /** - * {@inheritDoc} - */ - public boolean hasJsonPath(String path) { - boolean contains = true; - try { - get(path); - } catch (InvalidPathException e) { - contains = false; - } - return contains; - } - - /** - * {@inheritDoc} - */ - public boolean isNull(String path) { - return (null == get(path)); - } - - /** - * {@inheritDoc} - */ - @SuppressWarnings("unchecked") - public T get(String path) { - return (T) getByPath(Object.class, path); - } - - /** - * {@inheritDoc} - */ - public String getString(String path) { - return getByPath(String.class, path); - } - - /** - * {@inheritDoc} - */ - public Long getLong(String path) { - return getByPath(Long.class, path); - } - - /** - * {@inheritDoc} - */ - public Double getDouble(String path) { - return getByPath(Double.class, path); - } - - /** - * {@inheritDoc} - */ - public Boolean getBoolean(String path) { - return getByPath(Boolean.class, path); - } - - /** - * {@inheritDoc} - */ - public List getList(String path) { - return getByPath(List.class, path); - } - - /** - * {@inheritDoc} - */ - public Map getMap(String path) { - return getByPath(Map.class, path); - } - - - //------------------------------------------------------------ - // - // private methods - // - //------------------------------------------------------------ - - /* - private T getByPath(Class clazz, String stringPath) { - currentPath = ""; - Object current = this.root; - JSONPath path = new JSONPath(stringPath); - - while (path.hasMoreFragments()) { - - JSONPathFragment fragment = path.poll(); - - currentPath = fragment.appendToPath(currentPath); - - if (fragment.isArrayIndex()) { - current = toArray(current).get(fragment.getArrayIndex()); - } else if (fragment.isArrayWildcard()) { - current = getContainerValue(current, path.poll()); - } else { - current = getContainerValue(current, fragment); - } - } - return clazz.cast(current); - } - */ - - ///* - private T getByPath(Class clazz, String stringPath) { - currentPath = ""; - Object current = this.root; - Path path = new Path(stringPath); - - while (path.hasMoreFragments()) { - - PathFragment fragment = path.poll(); - - currentPath = fragment.appendToPath(currentPath); - - if (fragment.isArrayIndex()) { - current = toArray(current).get(fragment.getArrayIndex()); - } else if (fragment.isArrayWildcard()) { - current = getContainerValue(current, path.poll()); - } else { - - System.out.println("FRAGMENT " + fragment.toString()); - - current = getContainerValue(current, fragment); - - if (isArray(current) && path.hasMoreFragments() && !path.peek().isArrayIndex() && !path.peek().isArrayWildcard()) { - - JSONArray array = new JSONArray(); - - for (Object o : toArray(current)) { - String newPath = path.toString(); - - System.out.println("NEW PATH " + newPath); - - if (isDocument(o) || isArray(o)) { - - JsonReaderImpl sub = new JsonReaderImpl(o); - - Object o1 = sub.get(newPath); - //if(o instanceof Collection){ - array.add(o1); - //} - //else { - // array.addAll(l) - //} - - - } else { - System.out.println("hhhhhhh"); - array.add(o); - } - } - current = array; - break; - } - } - } - return clazz.cast(current); - } - - //*/ - private boolean isArray(Object obj) { - return (obj instanceof JSONArray); - } - - private boolean isDocument(Object obj) { - return (obj instanceof JSONObject); - } - - private JSONArray toArray(Object array) { - return (JSONArray) array; - } - - private JSONObject toDocument(Object document) { - return (JSONObject) document; - } - - /** - * Extracts a field from a given container. If the given container - * is an Array the field specified represents a field in the objects - * contained in the array. Values from all instances of this field - * will be returned in a List - * - * @param container a json document or array - * @param fragment the field to extract from the document alt. the documents contained in the array - * @return a single field value or a List of fields - */ - private Object getContainerValue(Object container, PathFragment fragment) { - Object result; - - if (container instanceof JSONArray) { - List list = new LinkedList(); - for (Object doc : toArray(container)) { - list.add(getContainerValue(doc, fragment)); - } - result = list; - - } else if (container instanceof JSONObject) { - JSONObject document = toDocument(container); - - if (!document.containsKey(fragment.value())) { - throw new InvalidPathException("Invalid path element: " + currentPath + " <=="); - } - - result = document.get(fragment.value()); - } else { - throw new InvalidPathException("Invalid path element: " + currentPath + " <=="); - } - return result; - } -} diff --git a/json-assert/src/main/java/com/jayway/jsonassert/impl/Path.java b/json-assert/src/main/java/com/jayway/jsonassert/impl/Path.java index 6ff54221..b694a6ee 100644 --- a/json-assert/src/main/java/com/jayway/jsonassert/impl/Path.java +++ b/json-assert/src/main/java/com/jayway/jsonassert/impl/Path.java @@ -55,6 +55,16 @@ class Path { //TODO: this needs some attention but will work for now Queue processed = new LinkedList(); + //fix initial deep scan + if(path.startsWith("..")){ + path = path.replaceFirst("\\.\\.", "\\*\\."); + } + + + //fix path scans + path = path.replace("..", ".*."); + + String[] split = path.split("[\\.|\\[]"); for (int i = 0; i < split.length; i++) { diff --git a/json-assert/src/main/java/com/jayway/jsonassert/impl/PathFragment.java b/json-assert/src/main/java/com/jayway/jsonassert/impl/PathFragment.java index 9c2f98bd..5f54ff93 100644 --- a/json-assert/src/main/java/com/jayway/jsonassert/impl/PathFragment.java +++ b/json-assert/src/main/java/com/jayway/jsonassert/impl/PathFragment.java @@ -10,6 +10,9 @@ import java.util.regex.Pattern; */ class PathFragment { + + public static final PathFragment WILDCARD_FRAGMENT = new PathFragment("*", false); + //matches array index accessers like : [1], [23] private static final Pattern ARRAY_POSITION_PATTER = Pattern.compile("\\[(\\d*)\\]"); @@ -102,6 +105,10 @@ class PathFragment { return ARRAY_WILDCARD_PATTER.matcher(value).matches() || GROOVY_WILDCARD_PATTER.matcher(value).matches(); } + boolean isWildcard(){ + return "*".endsWith(value()); + } + /** * returns the int index of this path fragment. If this is not an array index fragment * an UnsupportedOperationException is thrown diff --git a/json-assert/src/test/java/com/jayway/jsonassert/JsonPathSpecTest.java b/json-assert/src/test/java/com/jayway/jsonassert/JsonPathSpecTest.java new file mode 100644 index 00000000..85961ed2 --- /dev/null +++ b/json-assert/src/test/java/com/jayway/jsonassert/JsonPathSpecTest.java @@ -0,0 +1,105 @@ +package com.jayway.jsonassert; + +import com.jayway.jsonassert.impl.JsonPathImpl; +import org.junit.Test; + +import java.util.List; +import java.util.Map; + +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasItems; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +/** + * Created by IntelliJ IDEA. + * User: kallestenflo + * Date: 2/1/11 + * Time: 8:25 PM + */ +public class JsonPathSpecTest { + + public final static String DOCUMENT = + "{ \"store\": {\n" + + " \"book\": [ \n" + + " { \"category\": \"reference\",\n" + + " \"author\": \"Nigel Rees\",\n" + + " \"title\": \"Sayings of the Century\",\n" + + " \"price\": 8.95\n" + + " },\n" + + " { \"category\": \"fiction\",\n" + + " \"author\": \"Evelyn Waugh\",\n" + + " \"title\": \"Sword of Honour\",\n" + + " \"price\": 12.99\n" + + " },\n" + + " { \"category\": \"fiction\",\n" + + " \"author\": \"Herman Melville\",\n" + + " \"title\": \"Moby Dick\",\n" + + " \"isbn\": \"0-553-21311-3\",\n" + + " \"price\": 8.99\n" + + " },\n" + + " { \"category\": \"fiction\",\n" + + " \"author\": \"J. R. R. Tolkien\",\n" + + " \"title\": \"The Lord of the Rings\",\n" + + " \"isbn\": \"0-395-19395-8\",\n" + + " \"price\": 22.99\n" + + " }\n" + + " ],\n" + + " \"bicycle\": {\n" + + " \"color\": \"red\",\n" + + " \"price\": 19.95\n" + + " }\n" + + " }\n" + + "}"; + + @Test + public void the_authors_of_all_books_in_the_store() throws Exception { + JsonPath reader = JsonPathImpl.parse(DOCUMENT); + + assertThat(reader.getList("store.book[*].author"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien")); + } + + @Test + public void all_authors() throws Exception { + + JsonPath reader = JsonPathImpl.parse(DOCUMENT); + + assertThat(reader.getList("..author"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien")); + + } + + @Test + public void all_items_in_store() throws Exception { + JsonPath reader = JsonPathImpl.parse(DOCUMENT); + + List itemsInStore = reader.getList("store.*"); + + + assertEquals(JsonPathImpl.jsonPath(itemsInStore, "[0][0].author"), "Nigel Rees"); + + System.out.println(itemsInStore.toString()); + } + + @Test + public void the_price_of_everything_in_the_store() throws Exception { + JsonPath reader = JsonPathImpl.parse(DOCUMENT); + + assertThat(reader.getList("store..price"), hasItems(8.95D, 12.99D, 8.99D, 19.95D)); + } + + @Test + public void the_third_book() throws Exception { + JsonPath reader = JsonPathImpl.parse(DOCUMENT); + + Map book = reader.getReader("..book[2]").get("[0]"); + + assertThat(book, hasEntry("author", "Herman Melville")); + + + book = reader.getMap("store.book[2]"); + + assertThat(book, hasEntry("author", "Herman Melville")); + } + + +} diff --git a/json-assert/src/test/java/com/jayway/jsonassert/JsonReaderTest.java b/json-assert/src/test/java/com/jayway/jsonassert/JsonReaderTest.java deleted file mode 100644 index ba765d78..00000000 --- a/json-assert/src/test/java/com/jayway/jsonassert/JsonReaderTest.java +++ /dev/null @@ -1,300 +0,0 @@ -package com.jayway.jsonassert; - -import com.jayway.jsonassert.impl.JsonReaderImpl; -import org.hamcrest.Matchers; -import org.junit.Test; - -import java.io.InputStreamReader; -import java.text.ParseException; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.*; - -/** - * User: kalle stenflo - * Date: 1/20/11 - * Time: 9:31 AM - */ -public class JsonReaderTest { - - - private static String TEST_DOCUMENT = "{ \"nullField\" : null, \"stringField\" : \"string-field\" , \"numberField\" : 1234 , \"doubleField\" : 12.34 , \"booleanField\" : true , \"subDocument\" : {\"subField\" : \"sub-field\"} , \"stringList\" : [\"ONE\", \"TWO\"], \"objectList\" : [{\"subField\" : \"sub-field-0\", \"subDoc\": {\"subField\": \"A\"}}, {\"subField\" : \"sub-field-1\", \"subDoc\": {\"subField\": \"B\"}}], \"listList\" : [[\"0.0\", \"0.1\"], [\"1.0\", \"1.1\"]], }"; - private static String TEST_DOCUMENT_ARRAY = "{ \"listList\" : [[\"0.0\", \"0.1\"], [\"1.0\", \"1.1\"]], }"; - private static String TEST_DEEP_PATH_DOCUMENT = "{ \"a\" : { \"b\" : { \"c\" : { \"say\" : \"hello\" } } }}"; - private static String TEST_ARRAY = "[{\"name\" : \"name0\"}, {\"name\" : \"name1\"}]"; - private static String TEST_DEEP_PATH_DOCUMENT_ARRAY = "{ \"arr0\" : [{ \"arr0_0\" : [{ \"arr0_0_0\" : [{\"val\": \"0A\"}, {\"val\": \"1A\"}] }, { \"arr0_0\" : [{ \"arr0_0_0\" : [{\"val\": \"1A\"}, {\"val\": \"1B\"}] }] } ] }"; - - - - - - - @Test(expected = ParseException.class) - public void invalid_json_not_accepted() throws Exception { - JsonReaderImpl.parse("not json"); - } - - @Test - public void reader_can_be_created_with_input_stream() throws Exception { - - JsonPath reader = JsonAssert.parse(getInputStreamReader("json-test-doc.json"), true); - - assertEquals("donut", reader.getString("type")); - assertEquals("donut", reader.get("type")); - - assertThat(reader.getList("toppings"), Matchers.hasItems("Glazed", "Sugar")); - assertThat(reader.>get("toppings"), Matchers.hasItems("Glazed", "Sugar")); - } - - - @Test - public void a_string_field_can_be_accessed() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("string-field", reader.getString("stringField")); - assertEquals("string-field", reader.get("stringField")); - } - - @Test - public void is_null_returns_true_for_null_fields() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertTrue(reader.isNull("nullField")); - } - - @Test - public void is_null_returns_false_for_not_null_fields() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertFalse(reader.isNull("stringField")); - } - - - @Test - public void a_long_field_can_be_accessed() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertTrue(1234L == reader.getLong("numberField")); - assertEquals(1234L, reader.get("numberField")); - } - - @Test - public void a_double_field_can_be_accessed() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals(12.34D, reader.getDouble("doubleField"), 0.001); - assertEquals(12.34D, reader.get("doubleField"), 0.001); - - } - - @Test - public void a_boolean_field_can_be_accessed() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals(true, reader.getBoolean("booleanField")); - assertEquals(true, reader.get("booleanField")); - } - - @Test - public void a_path_can_be_checked_for_existence() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DEEP_PATH_DOCUMENT); - - assertTrue(reader.hasJsonPath("a.b.c.say")); - } - - @Test - public void a_path_can_be_checked_for_non_existence() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DEEP_PATH_DOCUMENT); - - assertFalse(reader.hasJsonPath("a.b.c.FOO")); - } - - @Test - public void a_string_field_can_be_accessed_in_a_nested_document() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("sub-field", reader.getString("subDocument.subField")); - assertEquals("sub-field", reader.get("subDocument.subField")); - } - - @Test - public void a_list_can_be_accessed_in_a_document() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals(2, reader.getList("stringList").size()); - assertEquals(2, reader.>get("stringList").size()); - } - - @Test - public void a_list_can_be_accessed_by_array_index() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("ONE", reader.getString("stringList[0]")); - assertEquals("TWO", reader.getString("stringList[1]")); - - assertEquals("ONE", reader.get("stringList[0]")); - assertEquals("TWO", reader.get("stringList[1]")); - } - - @Test - public void a_list_can_be_accessed_by_groovy_index() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("ONE", reader.getString("stringList.get(0)")); - assertEquals("TWO", reader.getString("stringList.get(1)")); - - assertEquals("ONE", reader.get("stringList.get(0)")); - assertEquals("TWO", reader.get("stringList.get(1)")); - } - - @Test - public void a_document_contained_in_a_list_can_be_accessed_by_array_index() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("sub-field-0", reader.getString("objectList[0].subField")); - assertEquals("sub-field-0", reader.get("objectList[0].subField")); - } - - - @Test - public void a_document_contained_in_a_list_can_be_accessed_by_groovy_index() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("sub-field-0", reader.getString("objectList.get(0).subField")); - assertEquals("sub-field-0", reader.get("objectList.get(0).subField")); - } - - @Test - public void an_array_in_an_array_can_be_accessed_by_array_index() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT_ARRAY); - - assertEquals("0.0", reader.getString("listList[0][0]")); - assertEquals("0.1", reader.getString("listList[0][1]")); - assertEquals("1.0", reader.getString("listList[1][0]")); - assertEquals("1.1", reader.getString("listList[1][1]")); - - assertEquals("0.0", reader.get("listList[0][0]")); - assertEquals("0.1", reader.get("listList[0][1]")); - assertEquals("1.0", reader.get("listList[1][0]")); - assertEquals("1.1", reader.get("listList[1][1]")); - } - - @Test - public void an_array_in_an_array_can_be_accessed_by_groovy_index() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT_ARRAY); - - assertEquals("0.0", reader.getString("listList.get(0).get(0)")); - assertEquals("0.1", reader.getString("listList.get(0).get(1)")); - assertEquals("1.0", reader.getString("listList.get(1).get(0)")); - assertEquals("1.1", reader.getString("listList.get(1).get(1)")); - - assertEquals("0.0", reader.get("listList.get(0).get(0)")); - assertEquals("0.1", reader.get("listList.get(0).get(1)")); - assertEquals("1.0", reader.get("listList.get(1).get(0)")); - assertEquals("1.1", reader.get("listList.get(1).get(1)")); - } - - @Test - public void an_array_with_documents_can_be_accessed_by_index() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_ARRAY); - - assertEquals("name0", reader.getString("[0].name")); - assertEquals("name1", reader.getString("[1].name")); - - assertEquals("name0", reader.get("[0].name")); - assertEquals("name1", reader.get("[1].name")); - } - - - @Test - public void a_nested_document_can_be_accessed_as_a_map() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("sub-field", reader.getMap("subDocument").get("subField")); - - assertEquals("sub-field", reader.get("subDocument").get("subField")); - } - - - @Test - public void a_deep_document_path_can_be_read() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DEEP_PATH_DOCUMENT); - - assertEquals("hello", reader.getString("a.b.c.say")); - - assertEquals("hello", reader.get("a.b.c.say")); - } - - @Test(expected = InvalidPathException.class) - public void exception_is_thrown_when_field_is_not_found() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - reader.getString("invalidProperty"); - } - - @Test(expected = InvalidPathException.class) - public void exception_is_thrown_when_field_is_not_found_with_get() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - reader.get("invalidProperty"); - } - - - @Test - public void array_wildcard_property_extract() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals(2, reader.getList("objectList[*].subField").size()); - - assertEquals(2, reader.>get("objectList[*].subField").size()); - - - } - - @Test - public void array_wildcard_property_extract_new() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("A", reader.getList("objectList.subDoc.subField").get(0)); - assertEquals("B", reader.getList("objectList.subDoc.subField").get(1)); - - assertEquals("A", reader.>get("objectList.subDoc.subField").get(0)); - assertEquals("B", reader.>get("objectList.subDoc.subField").get(1)); - - - } - - - @Test - public void list_to_string_returns_json() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("[\"ONE\",\"TWO\"]", reader.getList("stringList").toString()); - } - - - @Test - public void get_sub_reader_for_document() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("sub-field", reader.getReader("subDocument").getString("subField")); - } - - @Test - public void get_sub_reader_for_list() throws Exception { - JsonPath reader = JsonAssert.parse(TEST_DOCUMENT); - - assertEquals("ONE", reader.getReader("stringList").get("[0]")); - } - - - //---------------------------------------------------------- - // - // helpers - // - //---------------------------------------------------------- - private InputStreamReader getInputStreamReader(String resource) { - return new InputStreamReader(ClassLoader.getSystemResourceAsStream(resource)); - } -}