The Wayback Machine - https://web.archive.org/web/20240616191405/https://www.geeksforgeeks.org/how-to-convert-json-array-object-to-java-object/
Open In App

How to Convert JSON Array Object to Java Object?

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JSON arrays are useful for storing multiple values together that are related or part of the same set. For example, storing a list of items, user profiles, product catalog, etc. JSON arrays allow ordered access to the values using indices like in regular arrays in other languages (0 indexed).

Conversion Methods:

  • Using a JSON parsing library: Jackson & GSON
  • Iterating and parsing manually.

Steps to Convert JSON Array Object to Java Object

Below are the steps and implementation to convert JSON Array object to Java object using Jackson library.

Step 1: Create a Maven Project

Open any preferred IDE and create a new Maven project. Here we will be using IntelliJ IDEA, we can do this by selecting File -> New -> Project.. -> Maven and following the wizard.

Project Creation

Step 2: Add Jackson Dependency to POM.xml

Now, we will add Jackson dependency to the pom.xml file.

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>org.example</groupId>
    <artifactId>Java-Object</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.0</version> <!-- Use the latest version available -->
        </dependency>
 
    </dependencies>
    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
</project>


Step 3: Create the Java POJO Class

The User class defines a POJO to map JSON data with name and age properties. Getters and setters are provided for Jackson to populate objects.

User.java

Java




package org.example;
 
public class User
{
    private String firstName;
    private String lastName;
 
    private String email;
 
    public User() {}
    // Constructor Declaration
    public User(String firstName, String lastName,
                String email)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }
    // generate getters and setters
    public String getFirstName()
    {
      return firstName;
    }
 
    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }
 
    public String getLastName()
    {
      return lastName;
    }
 
    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }
 
    public String getEmail()
    {
      return email;
    }
 
    public void setEmail(String email)
    {
        this.email = email;
    }
}


Step 4: In the Main class add logic of Conversion JSON Array Object to Java Object

Now, we will add the logic to convert JSON Array Object to Java Object in the main class.

Java




package org.example;
 
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class Main {
    public static void main(String[] args)
    {
        try {
            // JSON string representing an array of user objects
            String jsonString = "[{\"firstName\":\"User1\",\"lastName\":\"XYZ\",\"email\":\"user1@example.com\"},"
                  + "{\"firstName\":\"User2\",\"lastName\":\"PQR\",\"email\":\"user2@example.com\"}]";
 
            // Create an ObjectMapper instance
            ObjectMapper objectMapper = new ObjectMapper();
 
            // Deserialize the JSON string into an array of User objects
            User[] users = objectMapper.readValue(jsonString, User[].class);
 
            // Print the details of each user
            for (User user : users) {
                System.out.println(
                    "First Name: " + user.getFirstName()
                    + ", Last Name: " + user.getLastName()
                    + ", Email: " + user.getEmail());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Output:

First Name: User1, Last Name: XYZ, Email: user1@example.com
First Name: User2, Last Name: PQR, Email: user2@example.com

Explanation of the Code:

  • In the above code, we have a JSON string jsonString representing an array of user objects.
  • We have created an ObjectMapper instance from the Jackson library, which helps with JSON processing.
  • We have used the readValue() method of the ObjectMapper to convert the JSON string into an array of User objects. We specify the type of the target array using User class.
  • Then we iterate over the array of User objects and print the details of each user.


Similar Reads

Java Program to Convert JSON String to JSON Object
Gson is a Java library that can be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects whose source code we don't have. It provides the support to transfer data in between different programming languages modules. JSON String Representation: The string must be in JSON f
2 min read
Convert Java Object to Json String using Jackson API
JSON stands for JavaScript Object Notation. It's a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. In order to convert a Java object into JSON, the following two me
3 min read
Convert Java Object to Json String using GSON
JSON Stand for JavaScript Object Notation. It's a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To convert a Java object into JSON, the following methods can be
2 min read
Convert Json String to Java Object Using GSON
Pre-requisite: Convert Java Object to Json String Using GSONJSON Stand for JavaScript Object Notation. It's a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To co
3 min read
Java JSON Processing (JSON-P) with Example
JSON (JavaScript Object Notation) is text-based lightweight technology. Nowadays it is a dominant and much-expected way of communication in the form of key-value pairs. It is an easier way of transmitting data as it is having nice formatted way. We can nest the objects and also can provide JSON arrays also. Implementation steps for a maven project
7 min read
What is JSON-Java (org.json)?
JSON(Javascript Object Notation) is a lightweight format of data exchange and it is independent of language. It is easily read and interpreted by humans and machines. Hence nowadays, everywhere JSON is getting used for transmitting data. Let us see how to prepare JSON data by using JSON.org JSON API in java JSON.simple is a library in java is used
5 min read
How to Convert JSON Array to String Array in Java?
JSON stands for JavaScript Object Notation. It is one of the widely used formats to exchange data by web applications. JSON arrays are almost the same as arrays in JavaScript. They can be understood as a collection of data (strings, numbers, booleans) in an indexed manner. Given a JSON array, we will discuss how to convert it into a String array in
3 min read
Java Program to Convert Byte Array to JSON
JSON is nothing but Javascript Object Notation. It is a text format to store the data as well as transport the data. Usually, it will be denoted in String value pairs. It is language-independent and can run anywhere. JSON notation contains the below basic elements. Hence the framed byte array (from any source it might have converted (i.e. via stati
4 min read
How to Convert an ArrayList of Objects to a JSON Array in Java?
In Java, an ArrayList is a resizable array implementation of the List interface. It implements the List interface and is the most commonly used implementation of List. In this article, we will learn how to convert an ArrayList of objects to a JSON array in Java. Steps to Convert an ArrayList of Objects to a JSON Array in JavaBelow are the steps and
3 min read
How to Convert a Vector of Objects into a JSON Array in Java?
In Java, the conversion of data structures like Vector to JSON (JavaScript Object Notation) format is required especially while working with the APIs or data interchange between different systems. The conversion of the Vector of an Object to the JSON Array has various approaches that we will learn in this article. Approaches for Converting Vector o
3 min read
Article Tags :
Practice Tags :