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


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"

Updated on: 09-Jul-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements