47

I have a HashMap object which I want to convert to JsonNode tree using com.fasterxml.jackson.databind.ObjectMapper. What is the best way to do it?

I found the following code but since I don't know the Jackson API well, I wonder if there are some better ways.

mapper.reader().readTree(mapper.writeValueAsString(hashmap))
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
cacert
  • 2,677
  • 10
  • 33
  • 56
  • What do you need the JsonNode instance for that a Hashmap can't achieve? – OneCricketeer Sep 08 '16 at 12:47
  • I think you should for loop and manual convert it :)... some think was wrong when you try convert by auto function because your object maybe not correctly with function required,, – HoangHieu Sep 08 '16 at 12:52

2 Answers2

110

The following will do the trick:

JsonNode jsonNode = mapper.convertValue(map, JsonNode.class);

Or use the more elegant solution pointed in the comments:

JsonNode jsonNode = mapper.valueToTree(map);

If you need to write your jsonNode as a string, use:

String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • 1
    This answer is a little more elegant IMHO: https://stackoverflow.com/questions/11828368/convert-java-object-to-jsonnode-in-jackson – Dasmowenator Jun 05 '17 at 20:47
3

First transform your map in a JsonNode :

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNodeMap = mapper.convertValue(myMap, JsonNode.class);

Then add this node to your ObjectNode with the set method :

myObjectNode.set("myMapName", jsonNodeMap);

To convert from JsonNode to ObjectNode use :

ObjectNode myObjectNode = (ObjectNode) myJsonNode;
Laurent
  • 469
  • 3
  • 7