Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JsonNode to ObjectNode

Tags:

java

json

jackson

I have a com.fasterxml JsonNode object with some data. I need to do some manipulation on its data. I googled for answer but didn't got it properly. Can you please suggest me how to manipulate JsonNode data. I have also tried to convert JsonNode to ObjectNode as follows

ObjectNode objectNode = (ObjectNode)filterJson; 

but its giving following exception....

java.lang.ClassCastException: com.fasterxml.jackson.databind.node.TextNode cannot be cast to  com.fasterxml.jackson.databind.node.ObjectNode 

please help!!

like image 958
Mr. Noddy Avatar asked Sep 22 '15 09:09

Mr. Noddy


People also ask

What is the difference between ObjectNode and JsonNode?

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.

What is a JsonNode in Java?

2.2. JsonNode. The JsonNode class represents a node in the JSON tree model. It can express JSON data in the following data types: Array, Binary, Boolean, Missing, Null, Number, Object, POJO, String. These data types are defined in the JsonNodeType enum.

What is difference between JsonNode and Jsonobject?

ObjectNode is a concrete implementation of JsonNode that maps a JSON object, and a JSON object is defined as following: An object is an unordered set of name/value pairs.


2 Answers

You can convert a JsonNode in an ObjectNode in this simple way:

ObjectNode objectNode = jsonNode.deepCopy(); 

Available from Jackson 2.0 and tested with Jackson 2.4.0

like image 116
Daniele Licitra Avatar answered Sep 22 '22 06:09

Daniele Licitra


Finally, I got the solution as follows...

JsonNode jsonNode = Json.toJson("Json String"); ObjectNode node = (ObjectNode) new ObjectMapper().readTree(jsonNode.asText()); //perform operations on node jsonNode = (JsonNode) new ObjectMapper().readTree(node.toString()); 

or another one as below...

ObjectNode node = (ObjectNode) new ObjectMapper().readTree("Json String") //perform operations on node jsonNode = (JsonNode) new ObjectMapper().readTree(node.toString()); 

but I don't know if this is good approach or not ? If there is any better than above, please let me know. Thank you!

like image 27
Mr. Noddy Avatar answered Sep 19 '22 06:09

Mr. Noddy