How To Convert Json Object To List In Java

JSON is called JavaScript Object Notation. In modern web development, exchanging data between applications is a common requirement. When working with JSON data in Java, it is common to convert JSON objects into lists for easier processing and manipulation. It’s a simple and lightweight data interchange format that is commonly used in web applications to exchange data.

In this blog, we will discuss different approaches and some sample problems as well. So, let’s start the journey of converting json objects to lists in java.

Why is converting a json object to a list in java needed?

Converting a json object to a list in java is needed. There are some reasons:

  • Data Extraction: Sometimes, JSON objects may contain nested data structures or arrays, and you may only be interested in extracting a particular array from the JSON object.
  • Data Processing: If you need to perform data processing operations such as filtering, sorting, aggregation on the data in a JSON object, converting it to a list can simplify the processing logic.
  • Data Analysis: If you are performing data analysis on JSON data, converting a JSON object to a list can be helpful for processing the data.

How to convert json object to list in java

Here are five different approaches to convert json object to list in java with detailed solution steps, code, and output for each approach:

  1. Using Jackson library
  2. Using Gson library
  3. Using JSON.simple library
  4. Manual approach using Java standard libraries
  5. Using Jackson library with TreeModel API

Let’s dive in more with examples to each approach.

Approach 1: Using Jackson library

Jackson is a sophisticated tool that offers an easy and resourceful method of analyzing and encoding JSON data. Its intrinsic ObjectMapper class allows for the conversion of JSON objects into Java objects, as well as lists.

Pros:

  • Powerful and flexible library with extensive features for parsing and serializing JSON data.
  • Supports various JSON formats, including JSON arrays, objects, and complex nested structures.
  • Provides good performance and memory efficiency.

Cons:

  • Requires additional library dependency (Jackson) to be added to the project.
  • Requires Java classes or Java beans to be defined for the JSON objects in advance.
  • May have a steeper learning curve compared to simpler JSON libraries.

Code:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

public class JsonToListUsingJackson {

    public static void main(String[] args) throws IOException {
        String json = "[{\"name\":\"John\", \"age\":30}, {\"name\":\"Jane\", \"age\":25}]";

        ObjectMapper mapper = new ObjectMapper();
        List<Person> people = mapper.readValue(json, new TypeReference<List<Person>>(){});

        System.out.println(people);
    }

    static class Person {
        String name;
        int age;

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}

Output:

[Person{name='John', age=30}, Person{name='Jane', age=25}]

Code Explanation:

  1. The code imports the Jackson library, which is a popular Java library used for parsing and generating JSON data.
  2. The code defines a JSON string that represents an array of person objects. Each person object contains a name and an age field.
  3. The code uses the ObjectMapper class from the Jackson library to map the JSON string to a List of Person objects. The TypeReference is used to specify the generic type of the List that we are expecting.
  4. The code defines a static inner class named Person, which represents a single person object with name and age fields. This class is used by Jackson to map the JSON data to Java objects.

Approach 2: Using Gson library

The utilization of Gson provides a convivial API that streamlines the process of parsing and serialization of JSON data. Developers are enabled to transform JSON objects to Java objects, such as lists, in a seamless manner through the utilization of the Gson class.

Pros:

  • Supports various JSON formats, including JSON arrays, objects, and complex nested structures.
  • Provides good performance and memory efficiency.

Cons:

  • Requires additional library dependency (Gson) to be added to the project.
  • Requires Java classes or Java beans to be defined for the JSON objects in advance.
  • May not be as feature-rich as some other JSON libraries like Jackson.

Code:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;

public class JsonToListUsingGson {

    public static void main(String[] args) {
        String json = "[{\"name\":\"Monu\", \"age\":28}, {\"name\":\"Disha\", \"age\":26}]";

        Gson gson = new Gson();
        List<Person> people = gson.fromJson(json, new TypeToken<List<Person>>(){}.getType());

        System.out.println(people);
    }

    static class Person {
        String name;
        int age;

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}

Output:

[Person{name='Monu', age=28}, Person{name='Disha', age=26}]

Code Explanation:

  1. Create a Gson object from the com.google.gson.Gson class.
  2. Call the fromJson() method of the Gson object with the input JSON string and the TypeToken object as parameters. The TypeToken object is used to preserve the generic type information of the list.
  3. The method returns a list of objects of the Person class that represents the input JSON array.
  4. Print the list of people.

Approach 3: Using JSON.simple library

JSON.simple is a lightweight JSON library that is here to revolutionize the way you handle JSON data. With its simplistic and minimalistic API, parsing and serializing JSON data has never been easier.

Pros:

  • Lightweight and simple library with a minimalistic API for parsing and serializing JSON data.
  • Does not require additional external dependencies.
  • Provides good performance and low memory footprint.

Cons:

  • Limited error handling capabilities, may not provide detailed error messages for malformed JSON data.
  • Requires manual handling of type conversions, as JSON.simple does not provide automatic type mapping.
  • May have limitations in handling advanced JSON features such as custom serializers or deserializers.

Code:

import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonToListUsingJsonSimple {

    public static void main(String[] args) {
        String json = "[{\"name\":\"Aakash\", \"age\":32}, {\"name\":\"Sonia\", \"age\":29}]";
        JSONParser parser = new JSONParser();
        List<Person> people = new ArrayList<>();
        try {
            JSONArray jsonArray = (JSONArray) parser.parse(json);
            for (Object obj : jsonArray) {
                JSONObject jsonObject = (JSONObject) obj;
                String name = (String) jsonObject.get("name");
                Long age = (Long) jsonObject.get("age");
                people.add(new Person(name, age.intValue()));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println(people);
    }

    static class Person {
        String name;
        int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}

Output:

[Person{name='Aakash', age=32}, Person{name='Sonia', age=29}]

Code Explanation:

  1. We first create a JSONParser object from the org.json.simple.parser.JSONParser class.
  2. We then parse the input JSON string using the parse() method of the JSONParser object. This returns an object of the org.json.simple.JSONArray class that represents the input JSON array.
  3. We iterate over the JSONArray object using a for loop and extract the name and age fields from each JSONObject.
  4. Finally, we create a new Person object with the extracted fields and add it to a list. We then print the list of people.

Approach 4: Manual approach using Java standard libraries

We have the power to convert JSON objects to a list through the expert employment of the org.json package. This particular package is one of the most eminent tools available in the vast arsenal of Java’s expansive toolset for the manipulation, interpretation, and serialization of JSON data.

Pros:

  • Does not require additional external dependencies, as it uses the standard Java libraries.
  • Suitable for simple JSON data with limited complexity.

Cons:

  • Requires manual parsing and handling of JSON data, which can be tedious and error-prone.
  • Lacks advanced features such as automatic type mapping or advanced error handling.
  • May require more code and effort compared to using dedicated JSON libraries.

Code:

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonToListManual {

    public static void main(String[] args) {
        String json = "[{\"name\":\"Ashwani\", \"age\":27}, {\"name\":\"Geeta\", \"age\":22}]";

        JSONArray jsonArray = new JSONArray(json);
        List<Person> people = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString("name");
            int age = jsonObject.getInt("age");
            people.add(new Person(name, age));
        }

        System.out.println(people);
    }

    static class Person {
        String name;
        int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}

Output:

[Person{name='Ashwani, age=27}, Person{name=Geeta', age=22}]

Code Explanation:

  1. Create a JSONArray object from the input JSON string using the org.json.JSONArray class.
  2. Iterate over the JSONArray object using a for loop and extract the fields of each JSONObject using the get() method.
  3. Print the list of people.

Approach 5: Using Jackson library with TreeModel API

The Jackson library is an exceptional tool for developers who require the ability to manipulate and traverse JSON data. This is made possible by the TreeModel API, which transforms JSON into a tree-like structure, allowing for comprehensive data analysis.

Pros:

  • Provides a flexible and powerful way to parse and manipulate JSON data using a tree-like structure.
  • Does not require Java classes or Java beans to be defined for the JSON objects in advance.
  • Supports complex nested structures and provides fine-grained control over the parsing process.

Cons:

  • May have a steeper learning curve compared to other approaches due to the complexity of the TreeModel API.
  • May not be suitable for simple JSON data with limited complexity, as it may involve more code and effort compared to other approaches.
  • Requires additional library dependency (Jackson) to be used.

Code:

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JsonToListUsingJacksonTreeModel {

    public static void main(String[] args) throws IOException {
        String json = "[{\"name\":\"Mayank\", \"age\":26}, {\"name\":\"Divya\", \"age\":20}]";

        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(json);
        List<Person> people = new ArrayList<>();
        Iterator<JsonNode> iterator = rootNode.elements();
        while (iterator.hasNext()) {
            JsonNode personNode = iterator.next();
            String name = personNode.get("name").asText();
            int age = personNode.get("age").asInt();
            people.add(new Person(name, age));
        }

        System.out.println(people);
    }

    static class Person {
        String name;
        int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}

Output:

[Person{name=Mayank', age=26}, Person{name='Divya, age=20}]

Code Explanation:

  1. Create an ObjectMapper object from the com.fasterxml.jackson.databind.ObjectMapper class.
  2. Call the readTree() method of the ObjectMapper object with the input JSON string as a parameter.
  3. The method returns a root JsonNode object representing the input JSON object.
  4. Traverse the JsonNode object using the elements() method and extract the fields of each JsonNode.

Best Approach To Convert a Json Object To List In Java

The qualities of the Jackson library approach for converting a json object to list are:

  • Powerful and flexible: Jackson is a feature-rich library with extensive capabilities for parsing and serializing JSON data. It supports various JSON formats, including arrays, and complex structures.
  • Good performance and memory efficiency: Jackson is known for its high performance and low memory usage. It has optimizations in place for efficient JSON parsing and serialization.
  • Type safety: Jackson requires Java classes or Java beans to be defined in advance for the JSON objects. This provides type safety, as the objects are deserialized into strongly-typed Java objects.

Sample Problems to Convert Json Object To List In Java

Sample Problem 1:

You are working on a finance management application that allows users to track their expenses and income. The application stores user transactions in a JSON file, with each transaction represented as a JSON object. You need to read the JSON file and convert the transactions to a list in Java so that you can perform further processing, such as calculating the net income for a particular time period.

Solution:

  1. Define the input JSON file that contains the list of transactions.
  2. Create an instance of the ObjectMapper class from the Jackson library.
  3. Use the readValue() method of the ObjectMapper class to read the JSON file and convert it to a List<Transaction> object.
  4. Iterate over the list of transactions to perform the necessary calculations.
  5. Print the results.

Code:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

public class JacksonJsonToList {

    public static void main(String[] args) throws IOException {
        // 1. Define the input JSON file that contains the list of transactions
        String filePath = "transactions.json";
        File jsonFile = new File(filePath);

        // 2. Create an instance of the ObjectMapper class from the Jackson library
        ObjectMapper objectMapper = new ObjectMapper();

        // 3. Use the readValue() method of the ObjectMapper class to read the JSON file and convert it to a List<Transaction> object
        List<Transaction> transactions = objectMapper.readValue(jsonFile, new TypeReference<List<Transaction>>(){});

        // 4. Iterate over the list of transactions to perform the necessary calculations
        BigDecimal netIncome = BigDecimal.ZERO;
        LocalDate startDate = LocalDate.of(2022, 1, 1);
        LocalDate endDate = LocalDate.of(2022, 3, 31);
        for (Transaction transaction : transactions) {
            LocalDate transactionDate = LocalDate.parse(transaction.getDate());
            if (transactionDate.isAfter(startDate.minusDays(1)) && transactionDate.isBefore(endDate.plusDays(1))) {
                if (transaction.getType().equals("income")) {
                    netIncome = netIncome.add(transaction.getAmount());
                } else if (transaction.getType().equals("expense")) {
                    netIncome = netIncome.subtract(transaction.getAmount());
                }
            }
        }

        // 5. Print the results
        System.out.println("Net Income for Q1 2022: " + netIncome);
    }

    static class Transaction {
        private String type;
        private BigDecimal amount;
        private String date;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public BigDecimal getAmount() {
            return amount;
        }

        public void setAmount(BigDecimal amount) {
            this.amount = amount;
        }

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }
    }
}

Output:

Net Income for Q1 2022: 2042.45

Sample Problem 2:

You are developing a conference management system, and you have a JSON object that represents a list of speakers with their details, including their name, email, organization, and talk title. You need to convert this JSON object to a list of Speaker objects in Java to perform further processing, such as filtering speakers based on their organization.

Solution:

  1. Define the input JSON string that represents a list of speakers with their details.
  2. Create a TypeToken that specifies the type of the destination list (List<Speaker> in this case).
  3. Create a Gson object.
  4. Call the fromJson() method of the Gson object with the input JSON string and the TypeToken object as parameters.
  5. The method returns a List<Speaker> object that represents the input JSON object.
  6. Filter the list of speakers based on their organization by using the stream() and filter() methods of the List interface.
  7. Print out the filtered list of speakers.

Code:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;
import java.util.stream.Collectors;

public class JsonToListSpeakers {

    public static void main(String[] args) {
        String json = "[{\"name\": \"John Doe\", \"email\": \"[email protected]\", \"organization\": \"Acme Corp\", \"talkTitle\": \"Introduction to Java\"}, {\"name\": \"Jane Smith\", \"email\": \"[email protected]\", \"organization\": \"XYZ Inc\", \"talkTitle\": \"Advanced Java Programming\"}]";

        // Create a TypeToken to specify the type of the destination list
        Type listType = new TypeToken<List<Speaker>>(){}.getType();

        // Create a Gson object
        Gson gson = new Gson();

        // Convert the JSON string to a List<Speaker> object
        List<Speaker> speakers = gson.fromJson(json, listType);

        // Filter the list of speakers based on their organization
        List<Speaker> filteredSpeakers = speakers.stream()
                .filter(speaker -> speaker.getOrganization().equals("Acme Corp"))
                .collect(Collectors.toList());

        // Print out the filtered list of speakers
        System.out.println("Filtered Speakers: " + filteredSpeakers);
    }

    static class Speaker {
        String name;
        String email;
        String organization;
        String talkTitle;

        @Override
        public String toString() {
            return "Speaker{" +
                    "name='" + name + '\'' +
                    ", email='" + email + '\'' +
                    ", organization='" + organization + '\'' +
                    ", talkTitle='" + talkTitle + '\'' +
                    '}';
        }

        public String getOrganization() {
            return organization;
        }
    }
}

Output:

Filtered Speakers: [Speaker{name='John Doe', email='[email protected]', organization='Acme Corp', talkTitle='Introduction to Java'}]

Sample Problem 3:

A JSON object which embodies a collection of Instagram posts and their corresponding captions and hashtags has been presented to you. In order to carry out additional procedures, including the extraction of hashtags from the captions.

Solution:

  1. We create a JSONParser object, which is the main class for parsing JSON data using the JSON.simple library.
  2. We iterate through each JSON object in the JSONArray and extract the relevant fields to create InstagramPost objects, where InstagramPost is a custom Java class representing an Instagram post with fields like postId, caption, and likes.
  3. We add the created InstagramPost objects to a list (postList) for further processing.
  4. This approach requires manual extraction of fields from the JSON objects, as JSON.simple library does not provide direct data binding capabilities like Jackson or Gson.

Code:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonToListInstagramPosts {

    public static void main(String[] args) throws IOException, ParseException {
        JSONParser parser = new JSONParser();

        // Read the input JSON file and parse it as a JSONObject
        Object obj = parser.parse(new FileReader("instagram_posts.json"));
        JSONObject jsonObject = (JSONObject) obj;

        // Get the "posts" array from the JSONObject
        JSONArray postsArray = (JSONArray) jsonObject.get("posts");

        // Create an empty list to store the InstagramPost objects
        List<InstagramPost> instagramPosts = new ArrayList<>();

        // Iterate over the posts array and convert each post to an InstagramPost object
        for (Object postObj : postsArray) {
            JSONObject post = (JSONObject) postObj;

            // Extract the post caption and hashtags
            String caption = (String) post.get("caption");
            List<String> hashtags = extractHashtags(caption);

            // Create a new InstagramPost object and add it to the list
            InstagramPost instagramPost = new InstagramPost(caption, hashtags);
            instagramPosts.add(instagramPost);
        }

        System.out.println(instagramPosts);
    }

    static class InstagramPost {
        String caption;
        List<String> hashtags;

        public InstagramPost(String caption, List<String> hashtags) {
            this.caption = caption;
            this.hashtags = hashtags;
        }

        @Override
        public String toString() {
            return "InstagramPost{" +
                    "caption='" + caption + '\'' +
                    ", hashtags=" + hashtags +
                    '}';
        }
    }

    private static List<String> extractHashtags(String caption) {
        List<String> hashtags = new ArrayList<>();
        String[] words = caption.split("\\s+");
        for (String word : words) {
            if (word.startsWith("#")) {
                hashtags.add(word.substring(1));
            }
        }
        return hashtags;
    }
}

Output:

[InstagramPost{caption='Enjoying the sunset #beach #vacation', hashtags=[beach, vacation]}, InstagramPost{caption='My first attempt at making sushi #sushi #cooking', hashtags=[sushi, cooking]}]

Sample Problem 4:

As an e-commerce platform manager, your task at hand involves inventory management for products in-store. The inventory data, presented in the form of a JSON object, necessitates a conversion into a list of objects to enable the implementation of essential operations such as adding, updating, and deleting products.

Solution:

  1. Define a JSON string that represents a list of products with their name, price, and stock values.
  2. Create a JSONObject instance from the JSON string and extract a JSONArray from it that contains the products.
  3. Iterate through the JSONArray, extract the values of each product object, create a Product instance with the extracted values, and add it to a List of products.
  4. Print the List of products to the console, which will display each product with its name, price, and stock values.

Code:

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;

public class JsonToListExample {
    public static void main(String[] args) {
        String jsonString = "{\"products\":[{\"name\":\"T-Shirt\",\"price\":15.99,\"stock\":100},{\"name\":\"Jeans\",\"price\":29.99,\"stock\":50},{\"name\":\"Sneakers\",\"price\":59.99,\"stock\":25}]}";

        JSONObject jsonObject = new JSONObject(jsonString);
        JSONArray jsonArray = jsonObject.getJSONArray("products");

        List<Product> productList = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject productObj = jsonArray.getJSONObject(i);
            String name = productObj.getString("name");
            double price = productObj.getDouble("price");
            int stock = productObj.getInt("stock");
            Product product = new Product(name, price, stock);
            productList.add(product);
        }

        // print the list of products
        System.out.println(productList);
    }
}

class Product {
    private String name;
    private double price;
    private int stock;

    public Product(String name, double price, int stock) {
        this.name = name;
        this.price = price;
        this.stock = stock;
    }

    @Override
    public String toString() {
        return "Product [name=" + name + ", price=" + price + ", stock=" + stock + "]";
    }
}

Output:

[Product [name=T-Shirt, price=15.99, stock=100], Product [name=Jeans, price=29.99, stock=50], Product [name=Sneakers, price=59.99, stock=25]]

Sample Problem 5:

You are working on the development of a mobile application that demands the management of user profiles. These profiles are received from a remote server in the form of a JSON object, requiring the conversion of said object to a list of user profile objects that are, in turn, displayed and manipulated within the confines of the app.

Solution:

  1. The code defines a class called UserProfile with three properties: name, age, and email.
  2. It then defines a main class called JsonToListExample, which reads a JSON string containing an array of user profiles and converts it to a list of UserProfile objects.
  3. The main class uses the Jackson ObjectMapper to parse the JSON string into a JsonNode object, then navigates to the “users” property of the root node to get an iterator of user nodes.
  4. For each user node, it extracts the name, age, and email properties and creates a new UserProfile object, which is added to a List<UserProfile> object. The resulting list is then printed to the console.

Code:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class UserProfile {
    private String name;
    private int age;
    private String email;

    public UserProfile(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getEmail() {
        return email;
    }
}

public class JsonToListExample {
    public static void main(String[] args) throws Exception {
        String json = "{ \"users\": [{\"name\":\"John\",\"age\":30,\"email\":\"[email protected]\"},{\"name\":\"Jane\",\"age\":25,\"email\":\"[email protected]\"}]}";
        
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(json);
        JsonNode usersNode = rootNode.path("users");

        Iterator<JsonNode> elements = usersNode.elements();
        List<UserProfile> userProfileList = new ArrayList<>();
        while (elements.hasNext()) {
            JsonNode userNode = elements.next();
            String name = userNode.path("name").asText();
            int age = userNode.path("age").asInt();
            String email = userNode.path("email").asText();
            userProfileList.add(new UserProfile(name, age, email));
        }

        System.out.println(userProfileList);
    }
}

Output:

[UserProfile{name='John', age=30, email='[email protected]'}, UserProfile{name='Jane', age=25, email='[email protected]'}]

Conclusion:

In conclusion, To convert a JSON object to a list in Java, you can use a popular library called Jackson, it is the best approach. Jackson provides a simple way to map JSON data to Java objects. We explored four different approaches also and discussed how to use them to convert JSON objects to lists. All the approaches have their own benefits and limitations but their usage depends as per the need of the project.