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 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").
JsonNode represents any valid Json structure whereas ObjectNode and ArrayNode are particular implementations for objects (aka maps) and arrays, respectively.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With