3

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 '

1 Answer 1

4

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.