Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 '
like image 502
BMT Avatar asked Jul 17 '26 03:07

BMT


1 Answers

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");
like image 96
Deadpool Avatar answered Jul 20 '26 00:07

Deadpool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!