Browse Source

Document context set method produces unexpected results for arrays #170

pull/182/head
Kalle Stenflo 9 years ago
parent
commit
3de1137b92
  1. 12
      json-path/src/main/java/com/jayway/jsonpath/spi/json/GsonJsonProvider.java
  2. 7
      json-path/src/main/java/com/jayway/jsonpath/spi/json/JacksonJsonNodeJsonProvider.java
  3. 1
      json-path/src/test/java/com/jayway/jsonpath/WriteTest.java
  4. 23
      json-path/src/test/java/com/jayway/jsonpath/old/IssuesTest.java

12
json-path/src/main/java/com/jayway/jsonpath/spi/json/GsonJsonProvider.java

@ -130,11 +130,15 @@ public class GsonJsonProvider extends AbstractJsonProvider {
@Override
public void setArrayIndex(Object array, int index, Object newValue) {
JsonArray a = toJsonArray(array);
if (index == a.size()) {
a.add(createJsonElement(newValue));
if (!isArray(array)) {
throw new UnsupportedOperationException();
} else {
a.set(index, createJsonElement(newValue));
JsonArray arr = toJsonArray(array);
if (index == arr.size()){
arr.add(createJsonElement(newValue));
}else {
arr.set(index, createJsonElement(newValue));
}
}
}

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

@ -131,7 +131,12 @@ public class JacksonJsonNodeJsonProvider extends AbstractJsonProvider {
if (!isArray(array)) {
throw new UnsupportedOperationException();
} else {
toJsonArray(array).insert( index, createJsonElement(newValue));
ArrayNode arrayNode = toJsonArray(array);
if (index == arrayNode.size()){
arrayNode.add(createJsonElement(newValue));
}else {
arrayNode.set(index, createJsonElement(newValue));
}
}
}

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

@ -317,5 +317,4 @@ public class WriteTest extends BaseTest {
return currentValue.toString()+"converted";
}
}
}

23
json-path/src/test/java/com/jayway/jsonpath/old/IssuesTest.java

@ -31,6 +31,7 @@ import static com.jayway.jsonpath.Criteria.PredicateContext;
import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;
import static com.jayway.jsonpath.JsonPath.read;
import static com.jayway.jsonpath.JsonPath.using;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
@ -957,4 +958,26 @@ public class IssuesTest extends BaseTest {
String object = path.read(json);
}
@Test
public void issue_170() {
String json = "{\n" +
" \"array\": [\n" +
" 0,\n" +
" 1,\n" +
" 2\n" +
" ]\n" +
"}";
DocumentContext context = using(JACKSON_JSON_NODE_CONFIGURATION).parse(json);
context = context.set("$.array[0]", null);
context = context.set("$.array[2]", null);
List<Integer> list = context.read("$.array", List.class);
assertThat(list).containsExactly(null, 1, null);
}
}

Loading…
Cancel
Save