Java ArrayNode-class And Method Code Example


Here is an example of using the ArrayNode class in the com.fasterxml.jackson.databind package in Java:

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

public class Example {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode arrayNode = mapper.createArrayNode();
        arrayNode.add("item1");
        arrayNode.add("item2");
        arrayNode.add("item3");
        // You can add other json nodes as well, like ObjectNode, TextNode etc
        JsonNode objectNode = mapper.createObjectNode().put("key", "value");
        arrayNode.add(objectNode);
        System.out.println(arrayNode);
    }
}

This example creates an instance of the ObjectMapper class, which is used to convert between Java objects and JSON. It also creates an instance of the ArrayNode class by calling createArrayNode method on ObjectMapper. With this, you can use the ArrayNode to add elements of different types like String, Integer, Boolean, JsonNode etc.

In this example, the add method is used to add 3 string values to the ArrayNode . It also shows how you can add other json nodes as well, like ObjectNode by creating it using mapper.createObjectNode() and adding it to the ArrayNode using add(JsonNode).

This example prints the ArrayNode as a json string to the console.

With this example, you can see how you can use the ArrayNode to create a JSON array, add elements to it, and use it with ObjectMapper.