Browse Source

code cleanup

pull/1/merge
kalle 14 years ago
parent
commit
e1de6a7086
  1. 9
      json-path-assert/src/test/java/com/jayway/jsonassert/JsonAssertTest.java
  2. 80
      json-path/src/main/java/com/jayway/jsonassert/JsonPath.java
  3. 282
      json-path/src/main/java/com/jayway/jsonassert/impl/JsonPathImpl.java
  4. 82
      json-path/src/main/java/com/jayway/jsonassert/impl/Path.java
  5. 129
      json-path/src/main/java/com/jayway/jsonassert/impl/PathFragment.java
  6. 2
      json-path/src/main/java/com/jayway/jsonpath/InvalidPathException.java
  7. 8
      json-path/src/main/java/com/jayway/jsonpath/JsonPath.java
  8. 25
      json-path/src/test/java/com/jayway/ScriptTest.java
  9. 105
      json-path/src/test/java/com/jayway/jsonassert/JsonPathSpecTest.java
  10. 278
      json-path/src/test/java/com/jayway/jsonassert/JsonPathTest.java
  11. 8
      json-path/src/test/java/com/jayway/jsonpath/JsonPathTest.java
  12. 1
      pom.xml

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

@ -56,6 +56,13 @@ public class JsonAssertTest {
public void list_content_can_be_asserted_with_matcher() throws Exception { public void list_content_can_be_asserted_with_matcher() throws Exception {
with(JSON).assertThat("$..book[*].author", hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien")); with(JSON).assertThat("$..book[*].author", hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"));
with(JSON).assertThat("$..author", hasItems("Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"));
}
@Test
public void list_content_can_be_asserted_with_nested_matcher() throws Exception {
with(JSON).assertThat("$..book[*]", hasItems( hasEntry("author", "Nigel Rees"), hasEntry("author", "Evelyn Waugh")) );
} }
@Test @Test
@ -63,6 +70,8 @@ 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"));
with(JSON).assertThat("$..book[0]", hasItems(hasEntry("category", "reference")));
} }
@Test @Test

80
json-path/src/main/java/com/jayway/jsonassert/JsonPath.java

@ -1,80 +0,0 @@
package com.jayway.jsonassert;
import java.util.List;
import java.util.Map;
/**
* User: kallestenflo
* Date: 1/24/11
* Time: 9:29 PM
*/
public interface JsonPath {
public enum ResultType {
PATH,
JSON
}
/**
* Get a new reader with the given path as root
*
* @param path to extract a reader for
* @return new reader
*/
JsonPath getReader(String path);
/**
* @param path
* @return
*/
boolean hasJsonPath(String path);
/**
* @param path
* @return
*/
boolean isNull(String path);
/**
* @param path
* @returnÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊ
*/
<T> T get(String path);
/**
* @param path
* @return
*/
String getString(String path);
/**
* @param path
* @return
*/
Long getLong(String path);
/**
* @param path
* @return
*/
Double getDouble(String path);
/**
* @param path
* @return
*/
Boolean getBoolean(String path);
/**
* @param path
* @param <T>
* @return
*/
<T> List<T> getList(String path);
/**
* @param path
* @return
*/
<T> Map<String, T> getMap(String path);
}

282
json-path/src/main/java/com/jayway/jsonassert/impl/JsonPathImpl.java

@ -1,282 +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.List;
import java.util.Map;
/**
* User: kalle stenflo
* Date: 2/1/11
* Time: 8:45 AM
* <p/>
* http://goessner.net/articles/JsonPath/
*/
public class JsonPathImpl implements JsonPath {
private static final JSONParser JSON_PARSER = new JSONParser();
private Object model;
public static synchronized JsonPath parse(Reader reader) throws java.text.ParseException, IOException {
try {
return new JsonPathImpl(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 JsonPathImpl(JSON_PARSER.parse(jsonDoc));
} catch (ParseException e) {
throw new java.text.ParseException(e.getMessage(), e.getPosition());
}
}
public static <T> 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<String, Object> document = toDocument(visit);
for (Map.Entry<String, Object> 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<String, Object> document = toDocument(visit);
for (Map.Entry<String, Object> 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())) {
throw new InvalidPathException();
}
Object current = toDocument(root).get(fragment.value());
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(current, path.clone(), ctx, strict);
}
} else {
PathFragment fragment = path.poll();
if (fragment.isArrayIndex()) {
Object extracted = toArray(root).get(fragment.getArrayIndex());
read(extracted, path.clone(), ctx, strict);
} else if (fragment.isArrayWildcard()) {
ctx.split();
for (Object extracted : toArray(root)) {
read(extracted, path.clone(), ctx, strict);
}
}
}
}
private static class ReaderContext {
private JSONArray result = new JSONArray();
private boolean pathSplit = false;
private void addResult(Object obj) {
result.add(obj);
}
private void split() {
pathSplit = true;
}
private boolean isPathSplit() {
return pathSplit;
}
}
private <T> T get(String jsonPath, boolean strict) {
Path path = new Path(jsonPath);
ReaderContext ctx = new ReaderContext();
read(model, path.clone(), ctx, strict);
if (ctx.isPathSplit()) {
return (T) ctx.result;
} else {
return (T) ctx.result.get(0);
}
}
public JsonPath getReader(String path) {
Object subModel = get(path);
if (!isArray(subModel) && !isDocument(subModel)) {
throw new InvalidPathException();
}
return new JsonPathImpl(subModel);
}
public boolean hasJsonPath(String path) {
boolean hasPath = true;
try {
get(path, true);
} catch (Exception e) {
hasPath = false;
}
return hasPath;
}
public boolean isNull(String path) {
return (get(path) == null);
}
public <T> T get(String jsonPath) {
return (T) get(jsonPath, false);
}
public String getString(String path) {
return get(path);
}
public Long getLong(String path) {
return get(path);
}
public Double getDouble(String path) {
return get(path);
}
public Boolean getBoolean(String path) {
return get(path);
}
public <T> List<T> getList(String path) {
return get(path);
}
public <T> Map<String, T> 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);
}
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;
}
}

82
json-path/src/main/java/com/jayway/jsonassert/impl/Path.java

@ -1,82 +0,0 @@
package com.jayway.jsonassert.impl;
import java.util.LinkedList;
import java.util.Queue;
/**
* User: kalle stenflo
* Date: 1/23/11
* Time: 1:52 PM
*/
class Path {
private final Queue<PathFragment> path;
Path(String path) {
this.path = compilePathFragments(path);
}
Path(Queue<PathFragment> path) {
this.path = new LinkedList<PathFragment>();
this.path.addAll(path);
}
int size() {
return path.size();
}
boolean hasMoreFragments() {
return !path.isEmpty();
}
PathFragment poll() {
return path.poll();
}
PathFragment peek() {
return path.peek();
}
@Override
protected Path clone() {
return new Path(path);
}
@Override
public String toString() {
String result = "";
for (PathFragment fragment : path) {
result = fragment.appendToPath(result);
}
return result;
}
private Queue<PathFragment> compilePathFragments(String path) {
//TODO: this needs some attention but will work for now
Queue<PathFragment> processed = new LinkedList<PathFragment>();
//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++) {
if (split[i].trim().length() > 0) {
String compiledFragment = split[i].endsWith("]") ? "[" + split[i] : split[i];
boolean isLeaf = (i == split.length - 1);
processed.add(new PathFragment(compiledFragment, isLeaf));
}
}
return processed;
}
}

129
json-path/src/main/java/com/jayway/jsonassert/impl/PathFragment.java

@ -1,129 +0,0 @@
package com.jayway.jsonassert.impl;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* User: kalle stenflo
* Date: 1/23/11
* Time: 1:55 PM
*/
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*)\\]");
//matches groovy style array index accessers like : get(1), get(23)
private static final Pattern GROOVY_POSITION_PATTER = Pattern.compile("get\\((\\d*)\\)");
//matches array wildcard : [*]
private static final Pattern ARRAY_WILDCARD_PATTER = Pattern.compile("\\[\\*\\]");
//matches groovy style array wildcard : [*]
private static final Pattern GROOVY_WILDCARD_PATTER = Pattern.compile("get\\(\\*\\)");
private final String value;
private final boolean leaf;
/**
* Creates a new path fragment
*
* @param value value of path fragment
* @param leaf
*/
PathFragment(String value, boolean leaf) {
this.value = value;
this.leaf = leaf;
}
@Override
public String toString() {
return "JSONPathFragment{" +
"value='" + value + '\'' +
'}';
}
/**
*
* @return the value of this path fragment
*/
String value() {
return value;
}
/**
* Utility method to rebuild a path from path fragments
*
* @param path the path to append this path fragment to
*
* @return the new extended path
*/
String appendToPath(String path){
StringBuilder builder = new StringBuilder(path);
if(ARRAY_POSITION_PATTER.matcher(value).matches()){
builder.append("[").append(getArrayIndex()).append("]");
}
else if(GROOVY_POSITION_PATTER.matcher(value).matches()){
builder.append(path.isEmpty()?"":".").append("get(").append(getArrayIndex()).append(")");
}
else if(ARRAY_WILDCARD_PATTER.matcher(value).matches()){
builder.append("[*]");
}
else if(GROOVY_WILDCARD_PATTER.matcher(value).matches()){
builder.append(path.isEmpty()?"":".").append("get(*)");
}
else {
builder.append(path.isEmpty()?"":".").append(value);
}
return builder.toString();
}
boolean isLeaf(){
return leaf;
}
/**
* Check if this path fragment is a array index
*
* @return true if this fragment is an array index
*/
boolean isArrayIndex() {
return ARRAY_POSITION_PATTER.matcher(value).matches() || GROOVY_POSITION_PATTER.matcher(value).matches();
}
/**
* Check if this path fragment is an array wildcard
*
* @return true if this fragment is an array wildcard
*/
boolean isArrayWildcard() {
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
*
* @return the array index of this fragment
*/
int getArrayIndex() {
Matcher matcher = ARRAY_POSITION_PATTER.matcher(value);
if (matcher.matches()) {
return Integer.parseInt(matcher.group(1));
}
matcher = GROOVY_POSITION_PATTER.matcher(value);
if (matcher.matches()) {
return Integer.parseInt(matcher.group(1));
}
throw new UnsupportedOperationException("not an array index fragment");
}
}

2
json-path/src/main/java/com/jayway/jsonassert/InvalidPathException.java → json-path/src/main/java/com/jayway/jsonpath/InvalidPathException.java

@ -1,4 +1,4 @@
package com.jayway.jsonassert; package com.jayway.jsonpath;
/** /**
* User: kalle stenflo * User: kalle stenflo

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

@ -27,6 +27,14 @@ public class JsonPath {
private JsonPath(String jsonPath) { private JsonPath(String jsonPath) {
if (jsonPath.matches("new ")) {
throw new InvalidPathException("Invalid path");
}
if (jsonPath.matches("[^\\?\\+\\=\\-\\*\\/\\!]\\(")) {
throw new InvalidPathException("Invalid path");
}
this.filters = new JsonPathFilterChain(PathUtil.splitPath(jsonPath)); this.filters = new JsonPathFilterChain(PathUtil.splitPath(jsonPath));
} }

25
json-path/src/test/java/com/jayway/ScriptTest.java

@ -1,25 +0,0 @@
package com.jayway;
import org.junit.Test;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
* Created by IntelliJ IDEA.
* User: kallestenflo
* Date: 2/3/11
* Time: 8:52 PM
*/
public class ScriptTest {
@Test
public void script() throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
System.out.println(engine.eval("1 === 2"));
System.out.println(engine.eval("'APA' === 'APA'").getClass());
}
}

105
json-path/src/test/java/com/jayway/jsonassert/JsonPathSpecTest.java

@ -1,105 +0,0 @@
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.<String>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.<String>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<Object> itemsInStore = reader.<Object>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.<Double>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<String, String> 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"));
}
}

278
json-path/src/test/java/com/jayway/jsonassert/JsonPathTest.java

@ -1,278 +0,0 @@
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.junit.Assert.*;
/**
* Created by IntelliJ IDEA.
* User: kallestenflo
* Date: 2/1/11
* Time: 10:08 AM
*/
public class JsonPathTest {
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
public void a_string_field_can_be_accessed() throws Exception {
JsonPath reader = JsonPathImpl.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 = JsonPathImpl.parse(TEST_DOCUMENT);
assertTrue(reader.isNull("nullField"));
}
@Test
public void is_null_returns_false_for_not_null_fields() throws Exception {
JsonPath reader = JsonPathImpl.parse(TEST_DOCUMENT);
assertFalse(reader.isNull("stringField"));
}
@Test
public void a_long_field_can_be_accessed() throws Exception {
JsonPath reader = JsonPathImpl.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 = JsonPathImpl.parse(TEST_DOCUMENT);
assertEquals(12.34D, reader.getDouble("doubleField"), 0.001);
assertEquals(12.34D, reader.<Double>get("doubleField"), 0.001);
}
@Test
public void a_boolean_field_can_be_accessed() throws Exception {
JsonPath reader = JsonPathImpl.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 = JsonPathImpl.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 = JsonPathImpl.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 = JsonPathImpl.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 = JsonPathImpl.parse(TEST_DOCUMENT);
assertEquals(2, reader.<String>getList("stringList").size());
assertEquals(2, reader.<List<String>>get("stringList").size());
}
@Test
public void a_list_can_be_accessed_by_array_index() throws Exception {
JsonPath reader = JsonPathImpl.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 = JsonPathImpl.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 = JsonPathImpl.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 = JsonPathImpl.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 = JsonPathImpl.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 = JsonPathImpl.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 = JsonPathImpl.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 = JsonPathImpl.parse(TEST_DOCUMENT);
assertEquals("sub-field", reader.getMap("subDocument").get("subField"));
assertEquals("sub-field", reader.<Map>get("subDocument").get("subField"));
}
@Test
public void a_deep_document_path_can_be_read() throws Exception {
JsonPath reader = JsonPathImpl.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 {
JSONReader reader = JsonQueryNew.parse(TEST_DOCUMENT);
reader.getString("invalidProperty");
}
*/
@Test
public void null_is_returned_when_field_is_not_found() throws Exception {
JsonPath reader = JsonPathImpl.parse(TEST_DOCUMENT);
assertNull(reader.getString("invalidProperty"));
}
public void null_is_when_field_is_not_found_with_get() throws Exception {
JsonPath reader = JsonPathImpl.parse(TEST_DOCUMENT);
assertNull(reader.get("invalidProperty"));
}
@Test
public void array_wildcard_property_extract() throws Exception {
JsonPath reader = JsonPathImpl.parse(TEST_DOCUMENT);
assertEquals(2, reader.<String>getList("objectList[*].subField").size());
assertEquals(2, reader.<List<String>>get("objectList[*].subField").size());
}
@Test
public void array_wildcard_property_extract_new() throws Exception {
JsonPath reader = JsonPathImpl.parse(TEST_DOCUMENT);
assertEquals("A", reader.<String>getList("objectList[*].subDoc.subField").get(0));
assertEquals("B", reader.<String>getList("objectList[*].subDoc.subField").get(1));
assertEquals("A", reader.<List<String>>get("objectList[*].subDoc.subField").get(0));
assertEquals("B", reader.<List<String>>get("objectList[*].subDoc.subField").get(1));
}
@Test
public void list_to_string_returns_json() throws Exception {
JsonPath reader = JsonPathImpl.parse(TEST_DOCUMENT);
assertEquals("[\"ONE\",\"TWO\"]", reader.getList("stringList").toString());
}
@Test
public void get_sub_reader_for_document() throws Exception {
JsonPath reader = JsonPathImpl.parse(TEST_DOCUMENT);
assertEquals("sub-field", reader.getReader("subDocument").getString("subField"));
}
@Test
public void get_sub_reader_for_list() throws Exception {
JsonPath reader = JsonPathImpl.parse(TEST_DOCUMENT);
assertEquals("ONE", reader.getReader("stringList").get("[0]"));
}
}

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

@ -139,12 +139,16 @@ public class JsonPathTest {
} }
@Test @Test
public void all_books_cheapier_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.<String>read(DOCUMENT, "$.store.book[?(@.price < 10)].title"), hasItems("Sayings of the Century", "Moby Dick"));
}
@Test
public void all_books_with_category_reference() throws Exception {
assertThat(JsonPath.<String>read(DOCUMENT, "$.store.book[?(@.category = 'reference')].title"), hasItems("Sayings of the Century")); assertThat(JsonPath.<String>read(DOCUMENT, "$..book[?(@.category = 'reference')].title"), hasItems("Sayings of the Century"));
} }

1
pom.xml

@ -85,6 +85,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration> <configuration>
<source>1.5</source> <source>1.5</source>
<target>1.5</target> <target>1.5</target>

Loading…
Cancel
Save