207

Is it possible to directly convert a Java Object to an JsonNode-Object?

The only way I found to solve this is to convert the Java Object to String and then to JsonNode:

ObjectMapper mapper = new ObjectMapper(); 
String json = mapper.writeValueAsString(object);
JsonNode jsonNode = mapper.readTree(json);
Max Schmidt
  • 7,377
  • 5
  • 23
  • 29
  • [This question](http://stackoverflow.com/questions/3653996/how-to-parse-a-json-string-into-jsonnode-in-jackson) may be helpful. – Leri Aug 06 '12 at 12:35
  • @PLB unfortunately not. I don't want to create a JSON-String. I want to directly convert a Java-Object to a JsonNode-Object – Max Schmidt Aug 06 '12 at 12:46

1 Answers1

392

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

Max Schmidt
  • 7,377
  • 5
  • 23
  • 29
  • 1
    It appears that ObjectMapper.valueToTree wasn't added until Jackson 1.6, so the alternative is great for those of us that haven't upgraded yet! – Steve Onorato Nov 07 '14 at 00:17
  • 1
    It is funny that valueToTree is implemented like write and read: https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java#L2542 :D – ortemij Dec 07 '15 at 16:13
  • Useful to know that the other way is also possible: there's a treeToValue method as well. – Jilles van Gurp Jun 23 '17 at 14:47
  • 3
    You can also use `ObjectNode node = mapper.convertValue(myObject, ObjectNode.class)` to convert directly to ObjectNode – Ares Jan 31 '20 at 13:53
  • I am trying to convert a java class into JsonNode. But getting nested exception is java.lang.IllegalArgumentException: Not an array .... ObjectMapper mapper = new ObjectMapper(); JsonNode jsonInput = mapper.convertValue(myJavaClass, JsonNode.class); Using Jackson-databind-2.11.0 – sashikanta Mar 25 '21 at 17:27