Browse Source

Fix for list element removel if multiple path elements match.

pull/81/head
Tamas Adam 10 years ago
parent
commit
48544d14ab
  1. 5
      json-path/src/main/java/com/jayway/jsonpath/internal/PathRef.java
  2. 8
      json-path/src/main/java/com/jayway/jsonpath/spi/json/AbstractJsonProvider.java
  3. 9
      json-path/src/test/java/com/jayway/jsonpath/WriteTest.java

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

@ -4,6 +4,7 @@ import com.jayway.jsonpath.*;
import com.jayway.jsonpath.spi.json.JsonProvider;
import java.util.Collection;
import java.util.List;
public abstract class PathRef implements Comparable<PathRef> {
@ -138,10 +139,12 @@ public abstract class PathRef implements Comparable<PathRef> {
private static class ArrayIndexPathRef extends PathRef {
private int index;
private Object value;
private ArrayIndexPathRef(Object parent, int index) {
super(parent);
this.index = index;
this.value = ((List<Object>) parent).get(index);
}
public void set(Object newVal, Configuration configuration){
@ -149,7 +152,7 @@ public abstract class PathRef implements Comparable<PathRef> {
}
public void delete(Configuration configuration){
configuration.jsonProvider().removeProperty(parent, index);
configuration.jsonProvider().removeProperty(parent, value);
}
public void add(Object value, Configuration configuration){

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

@ -106,16 +106,16 @@ public abstract class AbstractJsonProvider implements JsonProvider {
* Removes a value in an object or array
*
* @param obj an array or an object
* @param key a String key or a numerical index to remove
* @param key a String key or an object in a Collection to be removed.
*/
@SuppressWarnings("unchecked")
public void removeProperty(Object obj, Object key) {
if (isMap(obj))
((Map) obj).remove(key.toString());
else {
List list = (List) obj;
int index = key instanceof Integer ? (Integer) key : Integer.parseInt(key.toString());
list.remove(index);
Collection collection = (Collection) obj;
//int index = key instanceof Integer ? (Integer) key : Integer.parseInt(key.toString());
collection.remove(key);
}
}

9
json-path/src/test/java/com/jayway/jsonpath/WriteTest.java

@ -123,6 +123,15 @@ public class WriteTest extends BaseTest {
assertThat(res).containsExactly("reference");
}
@Test
public void an_array_criteria_with_multiple_results_can_be_deleted(){
String deletePath = "$._embedded.mandates[?(@.count=~/0/)]";
DocumentContext documentContext = JsonPath.parse(getClass().getResourceAsStream("/json_array_multiple_delete.json"));
documentContext.delete(deletePath);
List<Object> result = documentContext.read(deletePath);
assertThat(result.size()).isEqualTo(0);
}
@Test
public void multi_prop_delete() {

Loading…
Cancel
Save