How to convert HashMap to JsonNode with Jackson?

cacert :

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 :

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);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=421183&siteId=1