Deep Copy using Jackson: String or JsonNode

1,738 views
Skip to first unread message

Rad Akefirad

unread,
Apr 20, 2018, 10:45:26 AM4/20/18
to jackson-user
Hi,

I asked this question on SO and to my surprise I didn't get any answer. Is there anyone here know the answer.
Thanks in advance.

Regards,
Rad

PS: the post is:

Objective: deep copy (or clone) of a Java object
One of the suggested ways (almost everywhere) to do it is using Jackson:
 
MyPojo myPojo = new MyPojo();
ObjectMapper mapper = new ObjectMapper();
MyPojo newPojo = mapper.readValue(mapper.writeValueAsString(myPojo), MyPojo.class);


Question: is the following better in any way (e.g. performance)? is there any drawbacks?
 
MyPojo myPojo = new MyPojo();
ObjectMapper mapper = new ObjectMapper();
MyPojo newPojo = mapper.treeToValue(mapper.valueToTree(myPojo), MyPojo.class);
 

Tatu Saloranta

unread,
Apr 20, 2018, 1:18:11 PM4/20/18
to jackson-user
(note: thank you for including code from question here -- much appreciated!)

Second way should be bit more efficient since it only creates and uses
logical token stream but does not
have to encode JSON and then decode (parse) it to/from token stream.
So that is close to optimal regarding
Jackson.

About the only thing to make it even more optimal would be to directly
use `TokenBuffer` (which is what Jackson
itself uses for buffering). Something like:

TokenBuffer tb = new TokenBuffer(); // or one of factory methods
mapper.writeValue(tb, myPojo);
MyPojo copy = mapper.readValue(tb.asParser(), MyPojo.class);

This would further eliminate construction and traversal of the tree
model. I don't know how big a difference it'll
make, but is not much more code.

I wonder if it'd make sense to even expose this as new method in
`ObjectMapper`.... like `deepCopyValue(value)`?

If so, feel free to file an issue for `jackson-databind`: I could
easily add it, although would need to go to new minor/major
version, being API addition.

-+ Tatu +-

Rad Akefirad

unread,
Apr 23, 2018, 5:17:34 AM4/23/18
to jackson-user
Reply all
Reply to author
Forward
0 new messages