Browse Source

Improved array slicing.

pull/10/merge
Kalle Stenflo 11 years ago
parent
commit
ba23ae266a
  1. 8
      json-path/src/main/java/com/jayway/jsonpath/internal/filter/ArrayIndexFilter.java
  2. 51
      json-path/src/test/java/com/jayway/jsonpath/internal/filter/ArrayIndexFilterTest.java

8
json-path/src/main/java/com/jayway/jsonpath/internal/filter/ArrayIndexFilter.java

@ -62,7 +62,11 @@ public class ArrayIndexFilter extends PathTokenFilter {
String trimmedCondition = trim(this.trimmedCondition, 1, 0);
int get = Integer.parseInt(trimmedCondition);
for (int i = 0; i < get; i++) {
try {
jsonProvider.setProperty(result, jsonProvider.length(result), jsonProvider.getProperty(obj, i));
} catch (IndexOutOfBoundsException e){
break;
}
}
return result;
@ -78,6 +82,10 @@ public class ArrayIndexFilter extends PathTokenFilter {
int start = jsonProvider.length(obj) + get;
int stop = jsonProvider.length(obj);
if(start < 0){
start = 0;
}
for (int i = start; i < stop; i ++){
jsonProvider.setProperty(result, jsonProvider.length(result), jsonProvider.getProperty(obj, i));
}

51
json-path/src/test/java/com/jayway/jsonpath/internal/filter/ArrayIndexFilterTest.java

@ -0,0 +1,51 @@
package com.jayway.jsonpath.internal.filter;
import com.jayway.jsonpath.JsonPath;
import org.hamcrest.Matchers;
import org.junit.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* User: kalle
* Date: 9/9/13
* Time: 8:10 AM
*/
public class ArrayIndexFilterTest {
private static final String JSON = "[1, 3, 5, 7, 8, 13, 20]";
@Test
public void tail_does_not_throw_when_index_out_of_bounds() {
List<Integer> result = JsonPath.parse(JSON).read("$[-10:]");
assertThat(result, Matchers.contains(1, 3, 5, 7, 8, 13, 20));
}
@Test
public void head_does_not_throw_when_index_out_of_bounds() {
List<Integer> result = JsonPath.parse(JSON).read("$[:10]");
assertThat(result, Matchers.contains(1, 3, 5, 7, 8, 13, 20));
}
@Test
public void head_grabs_correct() {
List<Integer> result = JsonPath.parse(JSON).read("$[:3]");
assertThat(result, Matchers.contains(1, 3, 5));
}
@Test
public void tail_grabs_correct() {
List<Integer> result = JsonPath.parse(JSON).read("$[-3:]");
assertThat(result, Matchers.contains(8, 13, 20));
}
@Test
public void head_tail_grabs_correct() {
List<Integer> result = JsonPath.parse(JSON).read("$[0:3]");
assertThat(result, Matchers.contains(1, 3, 5));
}
}
Loading…
Cancel
Save