[Jackson API Examples] - How to convert JsonNode to ArrayNode in Java?

#JavaInspires

Hi Guys,

Welcome to Java Inspires.



In this post, we will see how to convert JsonNode to ArrayNode in Jackson API.

Here, we will a json using jackson api and print the values from array in json.

We will OjectMapper class from jackson, readTree() method to convert JSON string to JsonNode. Then we will get the field using get method from JsonNode and check for array type. If the jsonNode is isArray() method return true, we will type cast the JsonNode to ArrayNode.

This is sample json we are using.


{
	"name": "JavaInspires",
	"dataformats": [
		"Json",
		"XML",
		"Html",
		"Csv"
	]
}


Java Code:


package com.javainspires;

import java.io.IOException;

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

public class MainApp {

	public static void main(String[] args) throws IOException {
		
		// now we will see how to convert json string to jsonnode
		String sampleJSON = "{\n"
				+ "	\"name\": \"JavaInspires\",\n"
				+ "	\"dataformats\": [\n"
				+ "		\"Json\",\n"
				+ "		\"XML\",\n"
				+ "		\"Html\",\n"
				+ "		\"Csv\"\n"
				+ "	]\n"
				+ "}";
		// create object mapper class
		ObjectMapper mapper = new ObjectMapper();
		// convert json string to JsonNode
		JsonNode jsonNode = mapper.readTree(sampleJSON.getBytes());

		// check whether the node arraytype or not
		if (jsonNode.get("dataformats") != null && jsonNode.get("dataformats").isArray()) {
			// convert to array node
			ArrayNode arrayNode = (ArrayNode) jsonNode.get("dataformats");

			// iterate over this arraynode
			for (JsonNode node : arrayNode) {
				// print the text value
				System.out.println(node.textValue());
			}
		}
	}
}




Output:


Json
XML
Html
Csv


Jackson API POM:


		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.12.2</version>
		</dependency>


Jackson Docs:



Post a Comment

Previous Post Next Post