Change JSON Property Value with JsonPointer

1,592 views
Skip to first unread message

robert.p...@gdit.com

unread,
May 19, 2016, 4:13:13 PM5/19/16
to jackson-user
Hello,

I'm trying to change a property in a JSON tree by passing a JsonPointer string and a new property value into my method.  For example, in this JSON file:

{
  "name" : "John Smith",
  "id" : "12345",
  "address" : {
    "street" : "10 Main Street",
    "zip" : "22222"
  }
}

I would like to change the zip property by passing "/address/zip" and "55555".

Here is my latest attempt:

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonFile);
JsonPointer pointer = JsonPointer.compile("/address/zip");
JsonPointer head = pointer.head();
JsonPointer last = pointer.last();
JsonNode headNode = rootNode.at(head);
JsonNode lastNode = headNode.at(last);
// Use put() here on the head node using "55555" and the last node name, but nodes don't have names!

Is there another way?

Thanks.

Tatu Saloranta

unread,
May 19, 2016, 4:27:18 PM5/19/16
to jackson-user
Currently the issue is that you point to value (TextNode), but you really want to change the value of property, which is logically parent of match. And since JsonNode is single-linked (no parent linkage), there is no way to get back one level up.
Single-linking is by design as it allows for immutability of values, reuse, simplifies handling of many operations (including put).
But in this case it makes it impossible to do exactly what you'd like.

If we added something like "putAt(JsonPointer, value)" it would work, but wouldn't be available until next version.

As things are, you'd have to find JSON Object with "/address", and then do 'put("zip", value);" and that will work.

-+ Tatu +-


--
You received this message because you are subscribed to the Google Groups "jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jackson-user...@googlegroups.com.
To post to this group, send email to jackso...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages