使用 Jackson 的深度复制:String 或 JsonNode

Deep Copy using Jackson: String or JsonNode

Objective:Java 对象的深拷贝(或克隆)
建议的方法之一(几乎无处不在)是使用 Jackson:

MyPojo myPojo = new MyPojo();
ObjectMapper mapper = new ObjectMapper();
MyPojo newPojo = mapper.readValue(mapper.writeValueAsString(myPojo), MyPojo.class);

提问:下面那个比较好?在性能方面?有什么缺点吗?

MyPojo myPojo = new MyPojo();
ObjectMapper mapper = new ObjectMapper();
MyPojo newPojo = mapper.treeToValue(mapper.valueToTree(myPojo), MyPojo.class);

Tatu Saloranta 的回答:

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.

谢谢大图 :)