How to convert HashMap to JsonNode with Jackson? - java

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;

Related

How to convert a JsonNode containing a list of string to a comma separated string in Java

JsonNode:
{
name: ["bishal", "jaiswal", "Turtle"],
title: "jaiswal"
}
I want to extract the list of name from jsonNode as a comma separated string in an efficient way:
Output:
nameList ="bishal,jaiswal,Turtle"
Apart from converting the jsonNode of name array to a list & then using the join method to make the comma separated string. Any better way to do this ?
Here is the hack
ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonNode = objectMapper.readTree("{\"name\":[\"bishal\",\"jaiswal\",\"Turtle\"],\"title\":\"jaiswal\"}");
final JsonNode name = jsonNode.get("name");
final Iterator<JsonNode> iterator = name.iterator();
StringBuilder s = new StringBuilder();
while (iterator.hasNext()){
final JsonNode next = iterator.next();
if(s.length() > 0){
s.append(",");
}
s.append(next);
}
System.out.println(s.toString());
Hope so it will help you.
You can use Jackson JSON in this case...
Jackson is a very popular and efficient java based library to serialize or map Java objects to JSON and vice versa
For e.g.
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonData); //jsonData is your json string here...
JsonNode names = rootNode.path("name");
Iterator<JsonNode> elements = names.elements();
while(elements.hasNext()){
JsonNode name = elements.next();
System.out.println("Names are = "+name);
}
Please can you let me know if this has solved your problem? Thanks

How to retrieve a JSON element from a JsonNode object as String using jackson?

I'm pretty new to Jackson and Spring-Boot. I'm trying to parse the JsonNode object to retrieve a nested property from the JsonNode object as a string.
This is for a spring-boot application where I POST a json file into an ArrayList of my class object and then reading a single array element into JsonNode object. I have tried to cast the JsonNode object to an ArrayNode and then store the parent property into it using
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
JsonNode rootNode = mapper.valueToTree(workflow);
ArrayNode arrayNode = (ArrayNode) rootNode.get("metadata");
and then look for the required property in the arrayNode using
Iterator<JsonNode> arrayNodeIterator = arrayNode.elements();
while(arrayNodeIterator.hasNext()){
JsonNode jsonNode = arrayNodeIterator.next();
String str = jsonNode.get("name").asText();
}
Following is the json that I'm trying to read
{
"metadata": {
"name": "workflow-name"
},
"tasks": []
}
However, i'm getting following error on GET requests.
java.lang.ClassCastException: class com.fasterxml.jackson.databind.node.ObjectNode cannot be cast to class com.fasterxml.jackson.databind.node.ArrayNode (com.fasterxml.jackson.databind.node.ObjectNode and com.fasterxml.jackson.databind.node.ArrayNode are in unnamed module of loader '
From the above JSON metadata is JSONObject it is not ArrayNode
1) get the metadata as JsonNode
JsonNode rootNode = mapper.valueToTree(workflow);
JsonNode metaNode = rootNode.get("metadata");
2) Now get the name
System.out.println(metaNode.get("name").textValue());
3) tasks is ArrayNode so get the tasks as Array
ArrayNode arrayNode = (ArrayNode) rootNode.get("tasks");
try this example...
for more information check here https://www.baeldung.com/jackson-json-to-jsonnode
String jsonString = "{"k1":"v1","k2":"v2"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
// When
JsonNode jsonNode1 = actualObj.get("k1");
assertThat(jsonNode1.textValue(), equalTo("v1"));

java return json object with two json arrays

Hi in my playframework application I want to return an json object with multiple json nodes inside.
I tried this:
JsonNode kundeNode = Json.toJson(kunde);
JsonNode rechkopfNode = Json.toJson(rechkopf);
Json.newObject();
return ok(Json.newObject(
"kunde" -> kundeNode,
"rechKopf" -> rechkopfNode
));
But I got compiler errors. I think thats the scala synthax and not the java.
What would be the correct spelling?
Thanks in advance
You need to create a new ObjectNode and use the method .put() to populate your JSON object.
In your case :
JsonNode kundeNode = Json.toJson(kunde);
JsonNode rechkopfNode = Json.toJson(rechkopf);
ObjectNode json = Json.newObject();
json.put("kunde",kundeNode);
json.put("rechKopf",rechkopfNode);
return ok(json);

How to traverse a POJO type with jackson [duplicate]

This question already has an answer here:
Jackson: is there a way to serialize POJOs directly to treemodel?
(1 answer)
Closed 3 years ago.
Is it possible to directly convert a Java Object to an JsonNode-Object?
The only way I found to solve this is to convert the Java Object to String and then to JsonNode:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(object);
JsonNode jsonNode = mapper.readTree(json);
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?

Jackson JsonNode conversion - float precision problems

I need to convert an object to JsonNode because I need to manipulate the generated Json before returning it.
ObjectMapper mapper = new ObjectMapper();
Float f = 1.4f;
JsonNode node = mapper.convertValue(f, JsonNode.class)
Problem is, that node contains 1.399999976158142 instead of 1.4. Even if I serialize node to JSON...
String output = mapper.writeValueAsString(node);
.. output is 1.399999976158142
If I'm only using writeValueAsString, the result is correct.

Categories

Resources