How to convert JsonNode to ArrayNode using Jackson API in Java?

JavaJSONObject Oriented ProgrammingProgramming

A JsonNode is a base class for all JSON nodes that forms the JSON Tree Model whereas ArrayNode is a node class that represents an array mapped from JSON content. We can convert or translate JsonNode to ArrayNode by typecasting the ArrayNode to retrieve the values using the readTree() method of ObjectMapper class and get() method for accessing the value of a specified element of an array node.

Syntax

public JsonNode readTree(String content) throws IOException, com.fasterxml.jackson.core.JsonProcessingException

Example

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JSonNodeToArrayNodeTest {
   public static void main(String args[]) throws JsonProcessingException {
      String jsonStr = "{\"Technologies\" : [\"Java\", \"Scala\", \"Python\"]}";
      ObjectMapper mapper = new ObjectMapper();
      ArrayNode arrayNode = (ArrayNode) mapper.readTree(jsonStr).get("Technologies");
      if(arrayNode.isArray()) {
         for(JsonNode jsonNode : arrayNode) {
            System.out.println(jsonNode);
         }
      }
   }
}

Output

"Java"
"Scala"
"Python"
raja
Published on 19-Nov-2019 12:10:08
Advertisements