Is it possible to update a node's key names?

1,170 views
Skip to first unread message

Bilal Aslam

unread,
Apr 3, 2014, 1:59:38 PM4/3/14
to jackso...@googlegroups.com
Is it possible to **update** a key name in a JsonNode once it has been instantiated? My research shows that I need to create a *new* key and put in the node with the old value i.e. updating just the key is not possible.

Example: I have a nested JSON document I'm parsing with Jackson. I would like to rename keys in a nested node e.g. imagine if I have a Person who is represented like so:

{"name":"Bilal", "cat":{"name":"Mr. Bigglesworth", "grumpy":true }}

I want to change cat.grumpy to cat.hateful

{"name":"Bilal", "cat":{"name":"Mr. Bigglesworth", "hateful":true}}

The way I am doing it right now seems inefficient:

1) Person.java is a bean with Jackson annotations e.g.

class Person {
    private String personName;
    private JsonNode body;
    // getters, setters ommitted
}

2) Instantiate Person using an ObjectMapper.readvalue(parser, Person.class)
3) In the setBody method, I recursively iterate through keys in the "cat" JsonNode, creating new keys (e.g. "hateful") and putting them in the JsonNode with new key names.

One downside of my approach is that node order changes (yes, I know JSON nodes aren't ordered ... but it's still an annoying side-effect)

Tatu Saloranta

unread,
Apr 3, 2014, 6:09:25 PM4/3/14
to jackso...@googlegroups.com
On Thu, Apr 3, 2014 at 10:59 AM, Bilal Aslam <bi...@appuri.com> wrote:
Is it possible to **update** a key name in a JsonNode once it has been instantiated? My research shows that I need to create a *new* key and put in the node with the old value i.e. updating just the key is not possible.

JsonNode only exposes read-methods; to modify ObjectNodes and ArrayNodes you need to upcast them appropriately, to access mutators (put, add, insert). So methods are there, but since methods to modify contents are not relevant for most node types (scalar types), they are not exposed via JsonNode.

-+ Tatu +-



Reply all
Reply to author
Forward
0 new messages