简体   繁体   中英

How to convert HashMap to JsonNode with Jackson?

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

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM