
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert JSON Array to List Using Jackson in Java
Jackson is a Java-based library, and it can be useful for converting Java objects to JSON and JSON to Java objects. A Jackson API is faster than other API, needs less memory, and is good for large objects.
We can convert a JSON array to a list using the ObjectMapper class. It has a useful method, readValue(), which takes a JSON string and converts it to the object class specified in the second argument.
Before proceeding further, first of all, we need to import the Jackson library into our project. To do this, you can add the following dependency to your Maven pom.xml file -
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.3</version> </dependency>
Or if you do not use Maven, download the Jackson library JAR files and add them to your classpath.
Steps to convert a JSON array to a list using Jackson
- Create a class that represents the structure of the JSON objects.
- Use the ObjectMapper class to read the JSON array and convert it to a list of objects.
- Handle any exceptions that may occur during the conversion.
- Use the list as needed in your application.
Example
Following is the code that provides an example of how to convert a JSON array to a list using Jackson in Java:
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.io.IOException; import java.util.ArrayList; public class JsonArrayToList{ public static void main(String[] args) { String jsonArray = "[{"name":"John","age":30},{"name":"Jane","age":25}]"; ObjectMapper objectMapper = new ObjectMapper(); try { List<Person> personList = objectMapper.readValue(jsonArray, new TypeReference<List<Person>>(){}); for (Person person : personList) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge()); } } catch (IOException e) { e.printStackTrace(); } } } class Person { private String name; private int age; // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Output
Following is the output of the above code:
Name: John, Age: 30 Name: Jane, Age: 25