@Test public void key_val_can_be_added_to_root_object() { Map model = new HashMap(); model.put("a", "a-val"); String newVal = parse(model).put("$", "new-key", "new-val").read("$.new-key"); assertThat(newVal).isEqualTo("new-val"); }
@Test public void add_to_object() { Object res = parse(JSON_DOCUMENT).put("$.store.book[0]", "new-key", "new-value").read("$.store.book[0].new-key"); assertThat(res).isEqualTo("new-value"); }
@Test(expected = InvalidModificationException.class) public void add_to_object_on_array() { parse(JSON_DOCUMENT).put("$.store.book", "new-key", "new-value"); }
@Test // https://github.com/json-path/JsonPath/issues/364 public void setPropertyWithPOJO() { DocumentContext context = JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION).parse("{}"); UUID uuid = UUID.randomUUID(); context.put("$", "data", new Data(uuid)); String id = context.read("$.data.id", String.class); assertThat(id).isEqualTo(uuid.toString()); } // https://github.com/json-path/JsonPath/issues/366
@Test public void always_return_same_object() { // Test because of Bug #211 DocumentContext context = using(JACKSON_JSON_NODE_CONFIGURATION).parse(JSON_DOCUMENT); ObjectNode node1 = context.read("$"); ObjectNode child1 = new ObjectNode(JsonNodeFactory.instance); child1.put("name", "test"); context.put("$", "child", child1); ObjectNode node2 = context.read("$"); ObjectNode child2 = context.read("$.child"); assertThat(node1).isSameAs(node2); assertThat(child1).isSameAs(child2); }
/** * Adds or updates the value for a given key on the given path. * @param path The JSON path * @param key The JSON object key * @param value The new value * @param filters Optional JSON path filters * @return The new JSON fixture */ public JsonFixture put(final String path, final String key, final Object value, final Predicate... filters) { return new JsonFixture(cloneContext().put(path, key, value, filters)); }
private static void createParents(DocumentContext doc, String path) { StringUtils.Pair pathLeaf = getParentAndLeafPath(path); String left = pathLeaf.left; String right = pathLeaf.right; if ("".equals(left)) { // if root if (!"$".equals(right)) { // special case, root is array, typically "$[0]" doc.add("$", new LinkedHashMap()); // TODO we assume that second level is always object (not array of arrays) } return; } if (!pathExists(doc, left)) { createParents(doc, left); } Object empty; if (right.endsWith("]") && !right.endsWith("']")) { int pos = right.indexOf('['); right = right.substring(0, pos); List list = new ArrayList(); list.add(new LinkedHashMap()); empty = list; } else { empty = new LinkedHashMap(); } doc.put(left, right, empty); }