25

I've got a JsonNode that is provided by an external library. I need to convert this JsonNode into it's POJO representation.

I've seen methods like this:

mapper.readValue(jsonNode.traverse(), MyPojo.class);

But I'm not very happy with this sollution. traverse() will actually convert my JsonNode into a String representation before it is deserialized into a POJO. The performance is an issue for me in this case.

Any other way of doing it?

Thanks

pmartin8
  • 1,545
  • 1
  • 20
  • 36
  • Well, you could query the node to see what type it is and then deal with it as its "real" type. And, if necessary, write a `MyObject(jsonObject object)` constructor for your class, if you can't convince Jackson to do whatever it does. – Hot Licks Jul 29 '14 at 21:24
  • 1
    FWIW, traverse() will not construct a JSON String, but rather exposes nodes as tokens. It does have bit of overhead, so other approaches suggested below (convertValue(), treeToValue()) are preferable. But method you are using is ok as well. – StaxMan Jul 30 '14 at 17:53
  • 1
    possible duplicate of [Jackson - Convert JsonNode into POJO](http://stackoverflow.com/questions/19711695/jackson-convert-jsonnode-into-pojo) – icedtrees Sep 03 '15 at 04:31

1 Answers1

55

Perhaps you're looking for:

mapper.convertValue(jsonNode, MyPojo.class)
dnault
  • 8,340
  • 1
  • 34
  • 53
  • 6
    I think so; or even `mapper.treeToValue(jsonNode, MyPojo.class)` (not any shorter tho) – StaxMan Jul 30 '14 at 17:52
  • 2
    Well, according to the documentation this is a 2 step conversion so that's not much better than what I am doing I guess? Whats faster? traverse() or convertValue()? "Convenience method for doing two-step conversion from given value, into instance of given value type. This is functionality equivalent to first serializing given value into JSON, then binding JSON data into value of given type" – pmartin8 Jul 31 '14 at 00:10