Browse Source

removed readOne from JsonPath

pull/1/merge
kalle 14 years ago
parent
commit
e55e0a2aac
  1. 13
      json-path-assert/src/main/java/com/jayway/jsonassert/impl/JsonAsserterImpl.java
  2. 4
      json-path-assert/src/test/java/com/jayway/jsonassert/JsonAssertTest.java
  3. 68
      json-path/src/main/java/com/jayway/jsonpath/JsonPath.java
  4. 39
      json-path/src/main/java/com/jayway/jsonpath/filter/FilterOutput.java
  5. 2
      json-path/src/main/java/com/jayway/jsonpath/filter/JsonPathFilterBase.java
  6. 14
      json-path/src/main/java/com/jayway/jsonpath/filter/JsonPathFilterChain.java
  7. 79
      json-path/src/main/java/com/jayway/jsonpath/filter/ListFilter.java
  8. 32
      json-path/src/main/java/com/jayway/jsonpath/filter/PropertyFilter.java
  9. 4
      json-path/src/main/java/com/jayway/jsonpath/filter/RootFilter.java
  10. 6
      json-path/src/main/java/com/jayway/jsonpath/filter/TraverseFilter.java
  11. 56
      json-path/src/test/java/com/jayway/jsonpath/JsonPathTest.java

13
json-path-assert/src/main/java/com/jayway/jsonassert/impl/JsonAsserterImpl.java

@ -3,7 +3,6 @@ package com.jayway.jsonassert.impl;
import com.jayway.jsonassert.JsonAsserter; import com.jayway.jsonassert.JsonAsserter;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathUtil;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import static java.lang.String.format; import static java.lang.String.format;
@ -38,6 +37,14 @@ public class JsonAsserterImpl implements JsonAsserter {
String reason = "When processing json path: " + path; String reason = "When processing json path: " + path;
if (!matcher.matches(JsonPath.<T>read(jsonObject, path))) {
System.out.println(JsonPath.read(jsonObject, path).toString());
throw new AssertionError(reason + matcher.toString());
}
/*
if (PathUtil.isPathDefinite(path)) { if (PathUtil.isPathDefinite(path)) {
if (!matcher.matches(JsonPath.<T>readOne(jsonObject, path))) { if (!matcher.matches(JsonPath.<T>readOne(jsonObject, path))) {
throw new AssertionError(reason + matcher.toString()); throw new AssertionError(reason + matcher.toString());
@ -48,7 +55,7 @@ public class JsonAsserterImpl implements JsonAsserter {
throw new AssertionError(reason + matcher.toString()); throw new AssertionError(reason + matcher.toString());
} }
//MatcherAssert.assertThat(reason, (T) JsonPath.<T>read(jsonObject, path), matcher); //MatcherAssert.assertThat(reason, (T) JsonPath.<T>read(jsonObject, path), matcher);
} } */
return this; return this;
} }
@ -63,7 +70,7 @@ public class JsonAsserterImpl implements JsonAsserter {
* {@inheritDoc} * {@inheritDoc}
*/ */
public JsonAsserter assertNotDefined(String path) { public JsonAsserter assertNotDefined(String path) {
Object o = JsonPath.readOne(jsonObject, path); Object o = JsonPath.read(jsonObject, path);
if (o != null) { if (o != null) {
throw new AssertionError(format("Document contains the path <%s> but was expected not to.", path)); throw new AssertionError(format("Document contains the path <%s> but was expected not to.", path));

4
json-path-assert/src/test/java/com/jayway/jsonassert/JsonAssertTest.java

@ -104,7 +104,7 @@ public class JsonAssertTest {
with(JSON).assertThat("$.store.book[0]", hasEntry("category", "reference")) with(JSON).assertThat("$.store.book[0]", hasEntry("category", "reference"))
.assertThat("$.store.book[0]", hasEntry("title", "Sayings of the Century")) .assertThat("$.store.book[0]", hasEntry("title", "Sayings of the Century"))
.and() .and()
.assertThat("$..book[0]", hasItems(hasEntry("category", "reference"))) .assertThat("$..book[0]", hasEntry("category", "reference"))
.and() .and()
.assertThat("$.store.book[0]", mapContainingKey(equalTo("category"))) .assertThat("$.store.book[0]", mapContainingKey(equalTo("category")))
.and() .and()
@ -113,7 +113,7 @@ public class JsonAssertTest {
with(JSON).assertThat("$.['store'].['book'][0]", hasEntry("category", "reference")) with(JSON).assertThat("$.['store'].['book'][0]", hasEntry("category", "reference"))
.assertThat("$.['store'].['book'][0]", hasEntry("title", "Sayings of the Century")) .assertThat("$.['store'].['book'][0]", hasEntry("title", "Sayings of the Century"))
.and() .and()
.assertThat("$..['book'][0]", hasItems(hasEntry("category", "reference"))) .assertThat("$..['book'][0]", hasEntry("category", "reference"))
.and() .and()
.assertThat("$.['store'].['book'][0]", mapContainingKey(equalTo("category"))) .assertThat("$.['store'].['book'][0]", mapContainingKey(equalTo("category")))
.and() .and()

68
json-path/src/main/java/com/jayway/jsonpath/JsonPath.java

@ -1,6 +1,7 @@
package com.jayway.jsonpath; package com.jayway.jsonpath;
import com.jayway.jsonpath.filter.FilterOutput;
import com.jayway.jsonpath.filter.JsonPathFilterChain; import com.jayway.jsonpath.filter.JsonPathFilterChain;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
@ -104,8 +105,14 @@ public class JsonPath {
* @param <T> * @param <T>
* @return list of objects matched by the given path * @return list of objects matched by the given path
*/ */
public <T> List<T> read(Object json) { public <T> T read(Object json) {
return (List<T>) filters.filter(json); FilterOutput filterOutput = filters.filter(json);
if(filterOutput == null || filterOutput.getResult() == null){
return null;
}
return (T)filterOutput.getResult();
} }
/** /**
@ -115,8 +122,8 @@ public class JsonPath {
* @param <T> * @param <T>
* @return list of objects matched by the given path * @return list of objects matched by the given path
*/ */
public <T> List<T> read(String json) throws java.text.ParseException { public <T> T read(String json) throws java.text.ParseException {
return read(parse(json)); return (T)read(parse(json));
} }
/** /**
@ -137,8 +144,8 @@ public class JsonPath {
* @param <T> * @param <T>
* @return list of objects matched by the given path * @return list of objects matched by the given path
*/ */
public static <T> List<T> read(String json, String jsonPath) throws java.text.ParseException { public static <T> T read(String json, String jsonPath) throws java.text.ParseException {
return compile(jsonPath).read(json); return (T)compile(jsonPath).read(json);
} }
/** /**
@ -149,10 +156,11 @@ public class JsonPath {
* @param <T> * @param <T>
* @return list of objects matched by the given path * @return list of objects matched by the given path
*/ */
public static <T> List<T> read(Object json, String jsonPath) { public static <T> T read(Object json, String jsonPath) {
return compile(jsonPath).read(json); return (T)compile(jsonPath).read(json);
} }
/** /**
* Creates a new JsonPath and applies it to the provided Json object. Note this method * Creates a new JsonPath and applies it to the provided Json object. Note this method
* will throw an exception if the provided path returns more than one object. This method * will throw an exception if the provided path returns more than one object. This method
@ -163,23 +171,31 @@ public class JsonPath {
* @param <T> * @param <T>
* @return the object matched by the given path * @return the object matched by the given path
*/ */
public static <T> T readOne(Object json, String jsonPath) {
List<Object> result = compile(jsonPath).read(json, jsonPath);
if (log.isLoggable(Level.WARNING)) { // public static <T> T readOne(Object json, String jsonPath) {
if (!PathUtil.isPathDefinite(jsonPath)) { // Object result = compile(jsonPath).read(json, jsonPath);
log.warning("Using readOne() on a not definite json path may give incorrect results. Path : " + jsonPath); //
} // if (log.isLoggable(Level.WARNING)) {
} // if (!PathUtil.isPathDefinite(jsonPath)) {
// log.warning("Using readOne() on a not definite json path may give incorrect results. Path : " + jsonPath);
// }
// }
//
// return (T)result;
//
// /*
// if(result instanceof List){
// if (result.size() > 1) {
// throw new RuntimeException(format("Expected one result when reading path: %s but was: ", jsonPath, result.size()));
// }
// else if (result.isEmpty()){
// return null;
// }
// return (T) result.get(0);
// }
// */
// }
if (result.size() > 1) {
throw new RuntimeException(format("Expected one result when reading path: %s but was: ", jsonPath, result.size()));
}
else if (result.isEmpty()){
return null;
}
return (T) result.get(0);
}
/** /**
* Creates a new JsonPath and applies it to the provided Json object. Note this method * Creates a new JsonPath and applies it to the provided Json object. Note this method
@ -191,9 +207,9 @@ public class JsonPath {
* @param <T> * @param <T>
* @return the object matched by the given path * @return the object matched by the given path
*/ */
public static <T> T readOne(String json, String jsonPath) throws java.text.ParseException { // public static <T> T readOne(String json, String jsonPath) throws java.text.ParseException {
return (T) readOne(parse(json), jsonPath); // return (T) readOne(parse(json), jsonPath);
} // }
private static Object parse(String json) throws java.text.ParseException { private static Object parse(String json) throws java.text.ParseException {
try { try {

39
json-path/src/main/java/com/jayway/jsonpath/filter/FilterOutput.java

@ -0,0 +1,39 @@
package com.jayway.jsonpath.filter;
import java.util.List;
import static java.lang.String.format;
/**
* User: kalle stenflo
* Date: 2/9/11
* Time: 12:28 PM
*/
public class FilterOutput {
private final Object result;
public FilterOutput(Object result) {
this.result = result;
}
public boolean isList(){
return (result instanceof List);
}
public Object getResult() {
return result;
}
public List<Object> getResultAsList() {
if(!isList()){
throw new RuntimeException(format("Can not convert a %s to a %s", result.getClass().getName(), List.class.getName()));
}
return (List<Object>)result;
}
}

2
json-path/src/main/java/com/jayway/jsonpath/filter/JsonPathFilterBase.java

@ -9,5 +9,5 @@ import java.util.List;
* Time: 2:01 PM * Time: 2:01 PM
*/ */
public abstract class JsonPathFilterBase { public abstract class JsonPathFilterBase {
public abstract List<Object> apply(List<Object> filter); public abstract FilterOutput apply(FilterOutput filterItems);
} }

14
json-path/src/main/java/com/jayway/jsonpath/filter/JsonPathFilterChain.java

@ -29,20 +29,20 @@ public class JsonPathFilterChain {
return configured; return configured;
} }
public List<Object> filter(Object root) { public FilterOutput filter(Object root) {
List<Object> rootList = new JSONArray(); FilterOutput out = new FilterOutput(root);
rootList.add(root);
List<Object> result = rootList;
for (JsonPathFilterBase filter : filters) { for (JsonPathFilterBase filter : filters) {
if (filter == null) { if (filter == null) {
throw new InvalidPathException(); throw new InvalidPathException();
} }
result = filter.apply(result); if(out.getResult() == null){
return null;
}
out = filter.apply(out);
} }
return result; return out;
} }
} }

79
json-path/src/main/java/com/jayway/jsonpath/filter/ListFilter.java

@ -4,14 +4,15 @@ import com.jayway.jsonpath.JsonUtil;
import com.jayway.jsonpath.eval.ExpressionEvaluator; import com.jayway.jsonpath.eval.ExpressionEvaluator;
import org.json.simple.JSONArray; import org.json.simple.JSONArray;
//import javax.script.ScriptEngine;
//import javax.script.ScriptEngineManager;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
//import javax.script.ScriptEngine;
//import javax.script.ScriptEngineManager;
/** /**
* User: kalle stenflo * User: kalle stenflo
* Date: 2/2/11 * Date: 2/2/11
@ -37,31 +38,31 @@ public class ListFilter extends JsonPathFilterBase {
} }
@Override @Override
public List<Object> apply(List<Object> items) { public FilterOutput apply(FilterOutput items) {
List<Object> result = new JSONArray(); Object result = new JSONArray();
if (LIST_INDEX_PATTERN.matcher(pathFragment).matches()) { if (LIST_INDEX_PATTERN.matcher(pathFragment).matches()) {
return filterByListIndex(items); result = filterByListIndex(items.getResultAsList());
} else if (LIST_WILDCARD_PATTERN.matcher(pathFragment).matches()) { } else if (LIST_WILDCARD_PATTERN.matcher(pathFragment).matches()) {
return filterByWildcard(items); result = filterByWildcard(items.getResultAsList());
} else if (LIST_TAIL_PATTERN.matcher(pathFragment).matches()) { } else if (LIST_TAIL_PATTERN.matcher(pathFragment).matches()) {
return filterByListTailIndex(items); result = filterByListTailIndex(items.getResultAsList());
} else if (LIST_PULL_PATTERN.matcher(pathFragment).matches()) { } else if (LIST_PULL_PATTERN.matcher(pathFragment).matches()) {
return filterByPullIndex(items); result = filterByPullIndex(items.getResultAsList());
} else if (LIST_ITEM_HAS_PROPERTY_PATTERN.matcher(pathFragment).matches()) { } else if (LIST_ITEM_HAS_PROPERTY_PATTERN.matcher(pathFragment).matches()) {
return filterByItemProperty(items); result = filterByItemProperty(items.getResultAsList());
} else if (LIST_ITEM_MATCHES_EVAL.matcher(pathFragment).matches()) { } else if (LIST_ITEM_MATCHES_EVAL.matcher(pathFragment).matches()) {
return filterByItemEvalMatch(items); result = filterByItemEvalMatch(items.getResultAsList());
} }
return result; return new FilterOutput(result);
} }
private List<Object> filterByItemEvalMatch(List<Object> items) { private List<Object> filterByItemEvalMatch(List<Object> items) {
List<Object> result = new JSONArray(); List<Object> result = new JSONArray();
for (Object current : items) { for (Object current : items) {
for (Object item : JsonUtil.toList(current)) { for (Object item : items) {
if (isEvalMatch(item)) { if (isEvalMatch(item)) {
result.add(item); result.add(item);
} }
@ -76,8 +77,8 @@ public class ListFilter extends JsonPathFilterBase {
String prop = getFilterProperty(); String prop = getFilterProperty();
for (Object current : items) { //for (Object current : items) {
for (Object item : JsonUtil.toList(current)) { for (Object item : JsonUtil.toList(items)) {
if (JsonUtil.isMap(item)) { if (JsonUtil.isMap(item)) {
if (JsonUtil.toMap(item).containsKey(prop)) { if (JsonUtil.toMap(item).containsKey(prop)) {
@ -85,7 +86,7 @@ public class ListFilter extends JsonPathFilterBase {
} }
} }
} }
} //}
return result; return result;
} }
@ -94,50 +95,62 @@ public class ListFilter extends JsonPathFilterBase {
List<Object> result = new JSONArray(); List<Object> result = new JSONArray();
for (Object current : items) { for (Object current : items) {
if(current instanceof List){
result.addAll(JsonUtil.toList(current)); result.addAll(JsonUtil.toList(current));
} }
else {
result.add(current);
}
}
return result; return result;
} }
private List<Object> filterByListTailIndex(List<Object> items) { private Object filterByListTailIndex(List<Object> items) {
List<Object> result = new JSONArray();
//for (Object current : items) {
// Map array = JsonUtil.toMap(current);
for (Object current : items) { int index = getTailIndex(items.size());
List array = JsonUtil.toList(current);
return items.get(index);
result.add(array.get(getTailIndex(array.size())));
}
return result;
} }
private List<Object> filterByListIndex(List<Object> items) { private Object filterByListIndex(List<Object> items) {
List<Object> result = new JSONArray(); Object result = null;
for (Object current : items) { //for (Object current : items) {
List target = JsonUtil.toList(current); //List target = JsonUtil.toList(current);
Integer[] index = getArrayIndex(); Integer[] index = getArrayIndex();
if (index.length > 1) {
List<Object> tmp = new JSONArray();
for (int i : index) { for (int i : index) {
if(indexIsInRange(target, i)){ if (indexIsInRange(items, i)) {
result.add(target.get(i)); tmp.add(items.get(i));
}
} }
return result = tmp;
} else {
if (indexIsInRange(items, index[0])) {
result = items.get(index[0]);
} }
} }
//}
return result; return result;
} }
private List<Object> filterByPullIndex(List<Object> items) { private List<Object> filterByPullIndex(List<Object> items) {
List<Object> result = new JSONArray(); List<Object> result = new JSONArray();
for (Object current : items) { //for (Object current : items) {
List target = JsonUtil.toList(current); //List target = JsonUtil.toList(current);
Integer[] index = getListPullIndex(); Integer[] index = getListPullIndex();
for (int i : index) { for (int i : index) {
if(indexIsInRange(target, i)){ if (indexIsInRange(items, i)) {
result.add(target.get(i)); result.add(items.get(i));
}
} }
} }
//}
return result; return result;
} }

32
json-path/src/main/java/com/jayway/jsonpath/filter/PropertyFilter.java

@ -22,25 +22,45 @@ public class PropertyFilter extends JsonPathFilterBase {
} }
@Override @Override
public List<Object> apply(List<Object> filter) { public FilterOutput apply(FilterOutput filter) {
List<Object> result = new JSONArray(); List<Object> result = new JSONArray();
if (WILDCARD.equals(pathFragment)) { if (WILDCARD.equals(pathFragment)) {
for (Object current : filter) { if (filter.isList()) {
for (Object current : filter.getResultAsList()) {
for (Object value : JsonUtil.toMap(current).values()) { for (Object value : JsonUtil.toMap(current).values()) {
result.add(value); result.add(value);
} }
} }
} else {
for (Object value : JsonUtil.toMap(filter.getResult()).values()) {
result.add(value);
}
} }
else { return new FilterOutput(result);
for (Object current : filter) { } else {
if (filter.isList()) {
for (Object current : filter.getResultAsList()) {
if (JsonUtil.toMap(current).containsKey(pathFragment)) { if (JsonUtil.toMap(current).containsKey(pathFragment)) {
Object o = JsonUtil.toMap(current).get(pathFragment);
if (JsonUtil.isList(o)) {
result.addAll(JsonUtil.toList(o));
} else {
result.add(JsonUtil.toMap(current).get(pathFragment)); result.add(JsonUtil.toMap(current).get(pathFragment));
} }
} }
} }
return new FilterOutput(result);
return result; } else {
Object mapValue = null;
if (JsonUtil.toMap(filter.getResult()).containsKey(pathFragment)) {
mapValue = JsonUtil.toMap(filter.getResult()).get(pathFragment);
}
return new FilterOutput(mapValue);
}
}
} }
} }

4
json-path/src/main/java/com/jayway/jsonpath/filter/RootFilter.java

@ -11,7 +11,7 @@ import java.util.List;
public class RootFilter extends JsonPathFilterBase{ public class RootFilter extends JsonPathFilterBase{
@Override @Override
public List<Object> apply(List<Object> filter) { public FilterOutput apply(FilterOutput root) {
return filter; return root;
} }
} }

6
json-path/src/main/java/com/jayway/jsonpath/filter/TraverseFilter.java

@ -14,12 +14,12 @@ import java.util.List;
public class TraverseFilter extends JsonPathFilterBase { public class TraverseFilter extends JsonPathFilterBase {
@Override @Override
public List<Object> apply(List<Object> filter) { public FilterOutput apply(FilterOutput filter) {
List<Object> result = new JSONArray(); List<Object> result = new JSONArray();
traverse(filter, result); traverse(filter.getResult(), result);
return result; return new FilterOutput(result);
} }
private void traverse(Object container, List<Object> result) { private void traverse(Object container, List<Object> result) {

56
json-path/src/test/java/com/jayway/jsonpath/JsonPathTest.java

@ -6,6 +6,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@ -54,16 +55,16 @@ public class JsonPathTest {
@Test @Test
public void read_path_with_colon() throws Exception { public void read_path_with_colon() throws Exception {
assertEquals(JsonPath.readOne(DOCUMENT, "$.store.bicycle.foo:bar"), "fooBar"); assertEquals(JsonPath.read(DOCUMENT, "$.store.bicycle.foo:bar"), "fooBar");
assertEquals(JsonPath.readOne(DOCUMENT, "$.['store'].['bicycle'].['foo:bar']"), "fooBar"); assertEquals(JsonPath.read(DOCUMENT, "$.['store'].['bicycle'].['foo:bar']"), "fooBar");
} }
@Test @Test
public void read_document_from_root() throws Exception { public void read_document_from_root() throws Exception {
List<Object> list = JsonPath.read(DOCUMENT, "$.store"); Map result = JsonPath.read(DOCUMENT, "$.store");
assertEquals(2, ((Map) list.get(0)).values().size()); assertEquals(2, result.values().size());
} }
@ -73,7 +74,9 @@ public class JsonPathTest {
JsonPath path = JsonPath.compile("$.store.book[1]"); JsonPath path = JsonPath.compile("$.store.book[1]");
List<Map> list = path.read(DOCUMENT); Map map = path.read(DOCUMENT);
assertEquals("Evelyn Waugh", map.get("author"));
} }
@Test @Test
@ -86,14 +89,15 @@ public class JsonPathTest {
@Test @Test
public void read_store_book_author() throws Exception { public void read_store_book_author() throws Exception {
assertThat(JsonPath.<String>read(DOCUMENT, "$.store.book[*].author"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien")); assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[0,1].author"), hasItems("Nigel Rees", "Evelyn Waugh"));
assertThat(JsonPath.<String>read(DOCUMENT, "$.['store'].['book'][*].['author']"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien")); assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[*].author"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"));
assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.['store'].['book'][*].['author']"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"));
} }
@Test @Test
public void all_authors() throws Exception { public void all_authors() throws Exception {
assertThat(JsonPath.<String>read(DOCUMENT, "$..author"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien")); assertThat(JsonPath.<List<String>>read(DOCUMENT, "$..author"), hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"));
} }
@ -101,57 +105,57 @@ public class JsonPathTest {
public void all_store_properties() throws Exception { public void all_store_properties() throws Exception {
List<Object> itemsInStore = JsonPath.read(DOCUMENT, "$.store.*"); List<Object> itemsInStore = JsonPath.read(DOCUMENT, "$.store.*");
assertEquals(JsonPath.readOne(itemsInStore, "$.[0].[0].author"), "Nigel Rees"); assertEquals(JsonPath.read(itemsInStore, "$.[0].[0].author"), "Nigel Rees");
assertEquals(JsonPath.readOne(itemsInStore, "$.[0][0].author"), "Nigel Rees"); assertEquals(JsonPath.read(itemsInStore, "$.[0][0].author"), "Nigel Rees");
} }
@Test @Test
public void all_prices_in_store() throws Exception { public void all_prices_in_store() throws Exception {
assertThat(JsonPath.<Double>read(DOCUMENT, "$.store..price"), hasItems(8.95D, 12.99D, 8.99D, 19.95D)); assertThat(JsonPath.<List<Double>>read(DOCUMENT, "$.store..price"), hasItems(8.95D, 12.99D, 8.99D, 19.95D));
} }
@Test @Test
public void access_array_by_index_from_tail() throws Exception { public void access_array_by_index_from_tail() throws Exception {
assertThat(JsonPath.<String>readOne(DOCUMENT, "$..book[(@.length-1)].author"), equalTo("J. R. R. Tolkien")); assertThat(JsonPath.<String>read(DOCUMENT, "$..book[(@.length-1)].author"), equalTo("J. R. R. Tolkien"));
assertThat(JsonPath.<String>readOne(DOCUMENT, "$..book[-1:].author"), equalTo("J. R. R. Tolkien")); assertThat(JsonPath.<String>read(DOCUMENT, "$..book[-1:].author"), equalTo("J. R. R. Tolkien"));
} }
@Test @Test
public void read_store_book_index_0_and_1() throws Exception { public void read_store_book_index_0_and_1() throws Exception {
assertThat(JsonPath.<String>read(DOCUMENT, "$.store.book[0,1].author"), hasItems("Nigel Rees", "Evelyn Waugh")); assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[0,1].author"), hasItems("Nigel Rees", "Evelyn Waugh"));
assertTrue(JsonPath.<String>read(DOCUMENT, "$.store.book[0,1].author").size() == 2); assertTrue(JsonPath.<List>read(DOCUMENT, "$.store.book[0,1].author").size() == 2);
} }
@Test @Test
public void read_store_book_pull_first_2() throws Exception { public void read_store_book_pull_first_2() throws Exception {
assertThat(JsonPath.<String>read(DOCUMENT, "$.store.book[:2].author"), hasItems("Nigel Rees", "Evelyn Waugh")); assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[:2].author"), hasItems("Nigel Rees", "Evelyn Waugh"));
assertTrue(JsonPath.<String>read(DOCUMENT, "$.store.book[:2].author").size() == 2); assertTrue(JsonPath.<List>read(DOCUMENT, "$.store.book[:2].author").size() == 2);
} }
@Test @Test
public void read_store_book_filter_by_isbn() throws Exception { public void read_store_book_filter_by_isbn() throws Exception {
assertThat(JsonPath.<String>read(DOCUMENT, "$.store.book[?(@.isbn)].isbn"), hasItems("0-553-21311-3", "0-395-19395-8")); assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[?(@.isbn)].isbn"), hasItems("0-553-21311-3", "0-395-19395-8"));
assertTrue(JsonPath.<String>read(DOCUMENT, "$.store.book[?(@.isbn)].isbn").size() == 2); assertTrue(JsonPath.<List>read(DOCUMENT, "$.store.book[?(@.isbn)].isbn").size() == 2);
} }
@Test @Test
public void all_books_cheaper_than_10() throws Exception { public void all_books_cheaper_than_10() throws Exception {
assertThat(JsonPath.<String>read(DOCUMENT, "$.store.book[?(@.price < 10)].title"), hasItems("Sayings of the Century", "Moby Dick")); assertThat(JsonPath.<List<String>>read(DOCUMENT, "$.store.book[?(@.price < 10)].title"), hasItems("Sayings of the Century", "Moby Dick"));
} }
@Test @Test
public void all_books_with_category_reference() throws Exception { public void all_books_with_category_reference() throws Exception {
assertThat(JsonPath.<String>read(DOCUMENT, "$..book[?(@.category = 'reference')].title"), hasItems("Sayings of the Century")); assertThat(JsonPath.<List<String>>read(DOCUMENT, "$..book[?(@.category = 'reference')].title"), hasItems("Sayings of the Century"));
} }
@ -163,13 +167,15 @@ public class JsonPathTest {
@Test @Test
public void access_index_out_of_bounds_does_not_throw_exception() throws Exception { public void access_index_out_of_bounds_does_not_throw_exception() throws Exception {
List<Object> res = JsonPath.read(DOCUMENT, "$.store.book[100].author"); Object res = JsonPath.read(DOCUMENT, "$.store.book[100].author");
assertNull(res);
assertTrue(res.isEmpty()); res = JsonPath.read(DOCUMENT, "$.store.book[1, 200].author");
res = JsonPath.read(DOCUMENT, "$.store.book[100, 200].author");
assertTrue(res.isEmpty()); assertThat((List<String>)res, hasItems("Evelyn Waugh"));
//assertNull(();
} }
/* /*

Loading…
Cancel
Save