Browse Source

Fix ClassCastException when filer contains empty

This commit fixes the https://github.com/json-path/JsonPath/issues/900
pull/913/head
rosensilva 2 years ago
parent
commit
eb2dda3ddb
  1. 12
      json-path/src/main/java/com/jayway/jsonpath/internal/filter/ValueNodes.java
  2. 48
      json-path/src/test/java/com/jayway/jsonpath/EmptyFilterTest.java

12
json-path/src/main/java/com/jayway/jsonpath/internal/filter/ValueNodes.java

@ -170,7 +170,17 @@ public interface ValueNodes {
} }
public boolean isEmpty(Predicate.PredicateContext ctx) { public boolean isEmpty(Predicate.PredicateContext ctx) {
if (isArray(ctx) || isMap(ctx)) return ((Collection<?>) parse(ctx)).size() == 0; if (isArray(ctx) || isMap(ctx)) {
Object parsedObj = parse(ctx);
if (parsedObj instanceof Collection) {
return ((Collection<?>) parsedObj).size() == 0;
} else if (parsedObj instanceof Map) {
return ((Map<?, ?>) parsedObj).isEmpty();
} else {
throw new IllegalArgumentException("Expected a Collection or Map object, but got " +
parsedObj.getClass().getSimpleName());
}
}
else if((parse(ctx) instanceof String)) return ((String)parse(ctx)).length() == 0; else if((parse(ctx) instanceof String)) return ((String)parse(ctx)).length() == 0;
return true; return true;
} }

48
json-path/src/test/java/com/jayway/jsonpath/EmptyFilterTest.java

@ -0,0 +1,48 @@
package com.jayway.jsonpath;
import org.junit.Assert;
import org.junit.Test;
/**
* test for issue 900
*/
public class EmptyFilterTest {
@Test
public void test() {
String json = "{\n" +
" \"data1\": {\n" +
" \"data\": [\n" +
" {\n" +
" \"attribute1\": \"string1\",\n" +
" \"attribute2\": \"string2\"\n" +
" },\n" +
" {\n" +
" \"attribute1\": \"string3\",\n" +
" \"attribute2\": \"string4\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"data2\": {\n" +
" \"data\": [\n" +
" {}\n" +
" ]\n" +
" },\n" +
" \"data3\": {\n" +
" \"data\": [\n" +
" {\n" +
" \"attribute1\": \"string5\",\n" +
" \"attribute2\": \"string6\"\n" +
" },\n" +
" {\n" +
" \"attribute1\": \"string7\",\n" +
" \"attribute2\": \"string8\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
JsonPath jsonPath = JsonPath.compile("$..data.*[?(@ empty false)]");
Object jsonPathValue = jsonPath.read(json);
Assert.assertNotNull(jsonPathValue);
}
}
Loading…
Cancel
Save