Browse Source

fix issue #819 and add test cases

pull/820/head
sdww0 3 years ago
parent
commit
9a145021ea
  1. 3
      json-path/src/main/java/com/jayway/jsonpath/internal/function/text/Length.java
  2. 42
      json-path/src/test/java/com/jayway/jsonpath/internal/function/LengthFunctionTest.java

3
json-path/src/main/java/com/jayway/jsonpath/internal/function/text/Length.java

@ -49,6 +49,9 @@ public class Length implements PathFunction {
// for length - to the wildcard such that we request all of its children so we can get back an array and // for length - to the wildcard such that we request all of its children so we can get back an array and
// take its length. // take its length.
Parameter lengthOfParameter = parameters.get(0); Parameter lengthOfParameter = parameters.get(0);
if(lengthOfParameter.getPath().isDefinite()){
return ctx.configuration().jsonProvider().length(lengthOfParameter.getValue());
}
if (!lengthOfParameter.getPath().isFunctionPath()) { if (!lengthOfParameter.getPath().isFunctionPath()) {
Path path = lengthOfParameter.getPath(); Path path = lengthOfParameter.getPath();
if (path instanceof CompiledPath) { if (path instanceof CompiledPath) {

42
json-path/src/test/java/com/jayway/jsonpath/internal/function/LengthFunctionTest.java

@ -0,0 +1,42 @@
package com.jayway.jsonpath.internal.function;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for length function. Length class: {@link com.jayway.jsonpath.internal.function.text.Length}
*/
public class LengthFunctionTest {
private static final String testString = "{\n" +
"\t\"store\": {\n" +
"\t\t\"book\": [[\"book0-1\",\"book0-2\"],\"book1\", \"book2\", [\"book3\"]]" +
"\t},\n" +
" \"store1\": {\n" +
"\t\t\"book\": [\"book4\", [\"book5-1\",\"book5-2\"], \"book6\",[\"book7\"]]\n" +
"\t}\n" +
"}";
/**
* Test case for definite path
*/
@Test
public void testDefinite(){
assertThat((int)JsonPath.read(testString,"$.length($.store.book)")).isEqualTo(4);
assertThat((int)JsonPath.read(testString,"$.length($.store.book[0])")).isEqualTo(2);
assertThat((int)JsonPath.read(testString,"$.length($.store1.book)")).isEqualTo(4);
}
/**
* Test case for indefinite path
*/
@Test
public void testIndefinite(){
assertThat((int)JsonPath.read(testString,"$.length($..book)")).isEqualTo(8);
assertThat((int)JsonPath.read(testString,"$.length($.store..book)")).isEqualTo(4);
assertThat((int)JsonPath.read(testString,"$.length($.store1..book)")).isEqualTo(4);
assertThat((int)JsonPath.read(testString,"$.length($.store1..book[1])")).isEqualTo(2);
}
}
Loading…
Cancel
Save