Browse Source

GsonProvider

pull/55/head
Kalle Stenflo 10 years ago
parent
commit
d0a7d2f564
  1. 6
      json-path/pom.xml
  2. 1
      json-path/src/main/java/com/jayway/jsonpath/Criteria.java
  3. 7
      json-path/src/main/java/com/jayway/jsonpath/ReadContext.java
  4. 5
      json-path/src/main/java/com/jayway/jsonpath/internal/JsonReader.java
  5. 6
      json-path/src/main/java/com/jayway/jsonpath/internal/compiler/EvaluationContextImpl.java
  6. 2
      json-path/src/main/java/com/jayway/jsonpath/internal/compiler/PredicatePathToken.java
  7. 2
      json-path/src/main/java/com/jayway/jsonpath/internal/compiler/ScanPathToken.java
  8. 6
      json-path/src/main/java/com/jayway/jsonpath/internal/spi/json/AbstractJsonProvider.java
  9. 195
      json-path/src/main/java/com/jayway/jsonpath/internal/spi/json/GsonProvider.java
  10. 4
      json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonProvider.java
  11. 8
      json-path/src/test/java/com/jayway/jsonpath/ReturnTypeTest.java
  12. 7
      pom.xml
  13. 2
      system.properties

6
json-path/pom.xml

@ -35,6 +35,12 @@
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<optional>true</optional>
</dependency>
</dependencies> </dependencies>
<build> <build>

1
json-path/src/main/java/com/jayway/jsonpath/Criteria.java

@ -290,6 +290,7 @@ public class Criteria implements Predicate {
} else { } else {
try { try {
final Object actual = path.evaluate(ctx.target(), ctx.configuration()).getValue(); final Object actual = path.evaluate(ctx.target(), ctx.configuration()).getValue();
return criteriaType.eval(expected, actual, ctx.configuration()); return criteriaType.eval(expected, actual, ctx.configuration());
} catch (CompareException e) { } catch (CompareException e) {
return false; return false;

7
json-path/src/main/java/com/jayway/jsonpath/ReadContext.java

@ -16,6 +16,13 @@ package com.jayway.jsonpath;
public interface ReadContext { public interface ReadContext {
/**
* Returns the configuration used for reading
*
* @return an immutable configuration
*/
Configuration configuration();
/** /**
* Returns the JSON model that this context is reading * Returns the JSON model that this context is reading
* *

5
json-path/src/main/java/com/jayway/jsonpath/internal/JsonReader.java

@ -77,6 +77,11 @@ public class JsonReader implements ParseContext, ReadContext {
return parse(is); return parse(is);
} }
@Override
public Configuration configuration() {
return configuration;
}
//------------------------------------------------ //------------------------------------------------
// //
// ReadContext impl // ReadContext impl

6
json-path/src/main/java/com/jayway/jsonpath/internal/compiler/EvaluationContextImpl.java

@ -60,9 +60,9 @@ public class EvaluationContextImpl implements EvaluationContext {
if(resultIndex == 0){ if(resultIndex == 0){
throw new PathNotFoundException("No results for path: " + path.toString()); throw new PathNotFoundException("No results for path: " + path.toString());
} }
return (T) jsonProvider().getArrayIndex(valueResult, 0); return (T) jsonProvider().unwrap(jsonProvider().getArrayIndex(valueResult, 0));
} }
return (T) valueResult; return (T) jsonProvider().unwrap(valueResult);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -78,7 +78,7 @@ public class EvaluationContextImpl implements EvaluationContext {
public List<String> getPathList() { public List<String> getPathList() {
List<String> res = new ArrayList<String>(); List<String> res = new ArrayList<String>();
if(resultIndex > 0){ if(resultIndex > 0){
Iterable<Object> objects = configuration.getProvider().toIterable(pathResult); Iterable<?> objects = configuration.getProvider().toIterable(pathResult);
for (Object o : objects) { for (Object o : objects) {
res.add((String)o); res.add((String)o);
} }

2
json-path/src/main/java/com/jayway/jsonpath/internal/compiler/PredicatePathToken.java

@ -44,7 +44,7 @@ public class PredicatePathToken extends PathToken {
} }
} else if (ctx.jsonProvider().isArray(model)){ } else if (ctx.jsonProvider().isArray(model)){
int idx = 0; int idx = 0;
Iterable<Object> objects = ctx.jsonProvider().toIterable(model); Iterable<?> objects = ctx.jsonProvider().toIterable(model);
for (Object idxModel : objects) { for (Object idxModel : objects) {
if (accept(idxModel, ctx.configuration())) { if (accept(idxModel, ctx.configuration())) {

2
json-path/src/main/java/com/jayway/jsonpath/internal/compiler/ScanPathToken.java

@ -55,7 +55,7 @@ public class ScanPathToken extends PathToken {
predicateMatches.put(currentPath, model); predicateMatches.put(currentPath, model);
} }
Iterable<Object> models = ctx.jsonProvider().toIterable(model); Iterable<?> models = ctx.jsonProvider().toIterable(model);
int idx = 0; int idx = 0;
for (Object evalModel : models) { for (Object evalModel : models) {
String evalPath = currentPath + "[" + idx + "]"; String evalPath = currentPath + "[" + idx + "]";

6
json-path/src/main/java/com/jayway/jsonpath/internal/spi/json/AbstractJsonProvider.java

@ -23,6 +23,10 @@ import java.util.Map;
public abstract class AbstractJsonProvider implements JsonProvider { public abstract class AbstractJsonProvider implements JsonProvider {
public Object unwrap(Object obj){
return obj;
}
/** /**
* checks if object is an array * checks if object is an array
* *
@ -135,7 +139,7 @@ public abstract class AbstractJsonProvider implements JsonProvider {
* @return the entries for an array or the values for a map * @return the entries for an array or the values for a map
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Iterable<Object> toIterable(Object obj) { public Iterable<? extends Object> toIterable(Object obj) {
if (isArray(obj)) if (isArray(obj))
return ((Iterable) obj); return ((Iterable) obj);
else else

195
json-path/src/main/java/com/jayway/jsonpath/internal/spi/json/GsonProvider.java

@ -0,0 +1,195 @@
package com.jayway.jsonpath.internal.spi.json;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.internal.LazilyParsedNumber;
import com.jayway.jsonpath.InvalidJsonException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class GsonProvider extends AbstractJsonProvider {
private static final JsonParser parser = new JsonParser();
private static final Gson gson = new Gson();
public Object unwrap(Object o){
if(o == null){
return null;
}
if(!(o instanceof JsonElement)){
return o;
}
Object unwrapped = null;
JsonElement e = (JsonElement) o;
if(e.isJsonNull()) {
unwrapped = null;
} else if(e.isJsonPrimitive()){
JsonPrimitive p = e.getAsJsonPrimitive();
if(p.isString()){
unwrapped = p.getAsString();
} else if(p.isBoolean()){
unwrapped = p.getAsBoolean();
} else if(p.isNumber()){
Number n = p.getAsNumber();
if(n instanceof LazilyParsedNumber){
LazilyParsedNumber lpn = (LazilyParsedNumber) n;
BigDecimal bigDecimal = new BigDecimal(lpn.toString());
if(bigDecimal.scale() <= 0){
if(bigDecimal.compareTo(new BigDecimal(Integer.MAX_VALUE)) <= 0){
unwrapped = bigDecimal.intValue();
} else {
unwrapped = bigDecimal.longValue();
}
} else {
if(bigDecimal.compareTo(new BigDecimal(Float.MAX_VALUE)) <= 0){
unwrapped = bigDecimal.floatValue();
} else {
unwrapped = bigDecimal.doubleValue();
}
}
} else {
unwrapped = n;
}
}
} else {
unwrapped = o;
}
return unwrapped;
}
@Override
public Object parse(String json) throws InvalidJsonException {
return parser.parse(json);
}
@Override
public Object parse(Reader jsonReader) throws InvalidJsonException {
return parser.parse(jsonReader);
}
@Override
public Object parse(InputStream jsonStream) throws InvalidJsonException {
return parser.parse(new InputStreamReader(jsonStream));
}
@Override
public String toJson(Object obj) {
return ((JsonElement)obj).toString();
}
@Override
public Object createMap() {
return new JsonObject();
}
@Override
public Object createArray() {
return new JsonArray();
}
@Override
public boolean isArray(Object obj) {
return (obj instanceof JsonArray);
}
@Override
public Object getArrayIndex(Object obj, int idx) {
return toJsonArray(obj).get(idx);
}
@Override
public Object getMapValue(Object obj, String key) {
Object o = toJsonObject(obj).get(key);
if(o == null){
return UNDEFINED;
} else {
return o;
}
}
@Override
public void setProperty(Object obj, Object key, Object value) {
if (isMap(obj))
toJsonObject(obj).add(key.toString(), toJsonElement(value));
else {
JsonArray array = toJsonArray(obj);
int index;
if (key != null) {
index = key instanceof Integer ? (Integer) key : Integer.parseInt(key.toString());
} else {
index = array.size();
}
if(index == array.size()){
array.add(toJsonElement(value));
} else {
array.set(index, toJsonElement(value));
}
}
}
@Override
public boolean isMap(Object obj) {
return (obj instanceof JsonObject);
}
@Override
public Collection<String> getPropertyKeys(Object obj) {
List<String> keys = new ArrayList<String>();
for (Map.Entry<String, JsonElement> entry : toJsonObject(obj).entrySet()) {
keys.add(entry.getKey());
}
return keys;
}
@Override
public int length(Object obj) {
if (isArray(obj)) {
return toJsonArray(obj).size();
} else {
return toJsonObject(obj).entrySet().size();
}
}
@Override
public Iterable<?> toIterable(Object obj) {
if (isArray(obj)) {
return toJsonArray(obj);
} else {
List<JsonElement> values = new ArrayList<JsonElement>();
JsonObject jsonObject = toJsonObject(obj);
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
values.add(entry.getValue());
}
return values;
}
}
private JsonElement toJsonElement(Object o){
return gson.toJsonTree(o);
}
private JsonArray toJsonArray(Object o){
return (JsonArray) o;
}
private JsonObject toJsonObject(Object o){
return (JsonObject) o;
}
}

4
json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonProvider.java

@ -24,6 +24,8 @@ public interface JsonProvider {
static final Object UNDEFINED = new Object(); static final Object UNDEFINED = new Object();
public Object unwrap(Object obj);
Object parse(String json) throws InvalidJsonException; Object parse(String json) throws InvalidJsonException;
Object parse(Reader jsonReader) throws InvalidJsonException; Object parse(Reader jsonReader) throws InvalidJsonException;
@ -58,7 +60,7 @@ public interface JsonProvider {
* @param obj an array or an object * @param obj an array or an object
* @return the entries for an array or the values for a map * @return the entries for an array or the values for a map
*/ */
Iterable<Object> toIterable(Object obj); Iterable<?> toIterable(Object obj);
/** /**

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

@ -2,7 +2,6 @@ package com.jayway.jsonpath;
import org.junit.Test; import org.junit.Test;
import java.util.List;
import java.util.Map; import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -39,7 +38,12 @@ public class ReturnTypeTest extends BaseTest {
@Test @Test
public void assert_arrays_can_be_read() { public void assert_arrays_can_be_read() {
assertThat(reader.read("$.store.book", List.class)).hasSize(4);
Object result = reader.read("$.store.book");
assertThat(reader.configuration().getProvider().isArray(result)).isTrue();
assertThat(reader.configuration().getProvider().length(result)).isEqualTo(4);
} }
@Test @Test

7
pom.xml

@ -182,6 +182,13 @@
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version> <version>${jackson.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<dependency> <dependency>
<groupId>io.fastjson</groupId> <groupId>io.fastjson</groupId>
<artifactId>boon</artifactId> <artifactId>boon</artifactId>

2
system.properties

@ -1 +1 @@
java.runtime.version=1.7 java.runtime.version=1.6
Loading…
Cancel
Save