In Jackson, the JsonNode class represents a node in a JSON structure, which includes JSON objects, arrays, primitive values, etc., where an ArrayNode is a type of JsonNode that specifically represents a JSON array. In this article, we will see how to convert the JsonNode to ArrayNode.

Converting JsonNode to ArrayNode Using Jackson:

Using the methods provided by the ArrayNode class, we can convert the JsonNode to an ArrayNode. Following are the detailed steps:

1. Import the required classes and create an instance of ObjectMapper

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
ObjectMapper objectMapper = new ObjectMapper();

2. Create a JsonNode from a JSON string

String jsonString = "[{\"name\": \"Alice\"}, {\"name\": \"Bob\"}]";
JsonNode jsonNode = objectMapper.readTree(jsonString);

3. Convert the JsonNode to ArrayNode

ArrayNode arrayNode = objectMapper.createArrayNode();
arrayNode.add(jsonNode);

Following is the complete example:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

public class JsonNodeToArrayNodeExample {

    public static void main(String[] args) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();

            String jsonString = "[{\"name\": \"Alice\"}, {\"name\": \"Bob\"}]";
            JsonNode jsonNode = objectMapper.readTree(jsonString);

            ArrayNode arrayNode = objectMapper.createArrayNode();
            arrayNode.add(jsonNode);

            // Display the ArrayNode
            System.out.println("ArrayNode: " + arrayNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation:

In the above example, we imported the necessary classes from the Jackson Library and then created an instance of ObjectMapper, which is Jackson’s main class for reading and writing JSON data.

We also created a JsonNode by parsing a JSON string using the readTree() method of the ObjectMapper which represents an array of JSON objects.

Finally, we created an ArrayNode using the createArrayNode() method of the ObjectMapper. We then add the previously obtained JsonNode to the ArrayNode using the add() method.

References:

https://github.com/FasterXML/jackson-docs

Categorized in:

Tagged in: