Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HashMap to JsonNode with Jackson?

Tags:

java

json

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))
like image 487
cacert Avatar asked Sep 08 '16 12:09

cacert


People also ask

What is Jackson JsonNode?

The Jackson JsonNode class contains a set of methods that can convert a field value to another data type. For instance, convert a String field value to a long , or the other way around. Here is an example of converting a JsonNode field to some of the more common data types: String f2Str = jsonNode. get("f2").

What is the difference between JsonNode and ObjectNode?

JsonNode represents any valid Json structure whereas ObjectNode and ArrayNode are particular implementations for objects (aka maps) and arrays, respectively.

How do you find the value of JsonNode?

We can access a field, array or nested object using the get() method of JsonNode class. We can return a valid string representation using the asText() method and convert the value of the node to a Java int using the asInt() method of JsonNode class.


2 Answers

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);
like image 109
cassiomolin Avatar answered Oct 16 '22 06:10

cassiomolin


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;
like image 42
Laurent Avatar answered Oct 16 '22 07:10

Laurent