How to convert HashMap to JsonNode using Jackson?

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

I found the following code, but since I don't know the Jackson APIs well, I wonder if there are any more efficient ways.

 mapper.reader().readTree(mapper.writeValueAsString(hashmap)) 
+14
java json jackson
source share
2 answers

The following will do the trick:

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

Or use the more elegant solution mentioned in the comments :

 JsonNode jsonNode = mapper.valueToTree(map); 

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

 String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode); 
+30
source share

First convert your map to JsonNode:

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

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

 myObjectNode.set("myMapName", jsonNodeMap); 

To convert from JsonNode to ObjectNode use:

 ObjectNode myObjectNode = (ObjectNode) myJsonNode; 
0
source share

All Articles