How To Convert Json To List In Java

The realm of software development often requires the metamorphosis of data from one form to another. One routine yet imperative task is the conversion of JSON (JavaScript Object Notation) data into a list configuration in the Java programming language. JSON, a streamlined data interchange format, is facile to peruse and inscribe for both artificial intelligence entities and sentient beings alike. Conversely, a list, a data structure widely employed in Java, acts as a repository for an assemblage of elements.

The conversion of JSON to a list in Java, a multifarious endeavor, can prove useful in a sundry of contexts, such as when dissecting data from an API retort or poring over information from a file. This blog is dedicated to the elucidation of diverse methodologies to transform JSON data into a list in Java.

Why is converting json to list in java needed?

The art of converting JSON to a list in Java is a task of considerable utility in diverse scenarios. Let us explore some reasons why you might need to execute this conversion:

  1. API response parsing: A significant number of APIs furnish data in JSON format. If you wish to extract particular segments of this data and retain them in a list for further processing, you will require this conversion.
  2. Reading data from files: Supposing you have data stocked in a JSON file, it may prove expedient to convert it into a list for analysis or manipulation within your Java program.
  3. Data manipulation: At times, you may wish to manipulate data in list format, but solely have access to it in JSON format. In such cases, conversion of JSON data to a list format is essential before proceeding with any manipulations.

All in all, the task of converting JSON to a list in Java is a recurrent occurrence that can have far-reaching ramifications. Equipping yourself with this skill set can increase the versatility and adaptability of your Java programs when handling JSON data.

How to convert Json To List In Java

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

  1. Using Jackson Library
  2. Using Gson Library
  3. Using JSONArray Class
  4. Using TypeReference
  5. Using Manual Parsing
  6. Using Third-Party Tools

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

Approach 1: Using Jackson Library:

Jackson is a popular library for parsing JSON data in Java. It provides an ObjectMapper class that allows you to convert JSON strings to Java objects. Here’s how you can convert JSON to List using Jackson library

Pros:

  • Jackson is a widely-used library and has good community support.
  • It can handle complex JSON structures with ease.

Cons:

  • It can be slower than some other libraries.
  • It requires more configuration than some other libraries.

Code:

class Main {
  public static void main(String[] args) throws Exception {
    // Sample JSON string
    String jsonString = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Jane\"}]";

    // Create ObjectMapper object
    com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();

    // Convert JSON to List of Map
    java.util.List<java.util.Map<String, Object>> list = mapper.readValue(jsonString, new com.fasterxml.jackson.core.type.TypeReference<java.util.List<java.util.Map<String, Object>>>(){});

    // Print the list
    System.out.println(list);
  }
}

Output:

[{id=1, name=John}, {id=2, name=Jane}]

Code Explanation:

  1. We start by importing the necessary Jackson libraries.
  2. We define the JSON string that we want to convert to a List.
  3. We create an ObjectMapper object that we will use to convert the JSON to a List of Maps.
  4. We call the readValue() method of the ObjectMapper object and pass it the JSON string and a TypeReference that specifies the type of the output we want (a List of Maps).
  5. Finally, we print the resulting List.

Approach 2: Using Gson Library:

Gson is another popular library for parsing JSON data in Java. It provides a Gson class that allows you to convert JSON strings to Java objects. Here’s how you can convert JSON to List using Gson library

Pros:

  • Gson is a lightweight and fast library.
  • It has a simple API and requires minimal configuration.

Cons:

  • It may not handle complex JSON structures as well as other libraries.
  • It has less community support compared to some other libraries.

Code:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Sample JSON string
        String jsonString = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Jane\"}]";

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

        // Convert JSON to List of Map
        List<Map<String, Object>> list = gson.fromJson(jsonString, new TypeToken<List<Map<String, Object>>>(){}.getType());

        // Print the list
        System.out.println(list);
    }
}

Output:

[{id=1, name=John}, {id=2, name=Jane}]

Code Explanation:

  1. We start by importing the necessary Gson library.
  2. We define the JSON string that we want to convert to a List.
  3. We create a Gson object that we will use to convert the JSON to a List of Maps.
  4. We call the fromJson() method of the Gson object and pass it the JSON string and a TypeToken that specifies the type of the output we want (a List of Maps).
  5. Finally, we print the resulting List.

Approach 3: Using JSONArray Class:

Java provides a JSONArray class that allows you to represent an array in JSON format. Here’s how you can convert JSON to List using the JSONArray class.

Pros:

  • It’s a built-in Java class and requires no external library.
  • It’s easy to use for simple JSON structures.

Cons:

  • It can be more verbose than some other libraries.
  • It may not handle complex JSON structures as well as other libraries.
  •  

Code:

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

import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Sample JSON string
        String jsonString = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Jane\"}]";

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

        // Convert JSON to List of Map
        List<Map<String, Object>> list = gson.fromJson(jsonString, new TypeToken<List<Map<String, Object>>>(){}.getType());

        // Print the list
        System.out.println(list);
    }
}

Output:

[{id=1, name=John}, {id=2, name=Jane}]

Code Explanation:

  1. We start by importing the org.json library.
  2. We define the JSON string that we want to convert to a List.
  3. We create an empty List to hold the parsed data.
  4. We create a JSONArray object from the JSON string.
  5. We loop through the JSONArray and convert each element to a Map.
  6. Finally, we add each Map to the List and print the resulting List.

Approach 4: Using TypeReference:

TypeReference is a class in Jackson library that allows you to specify the type of the output you want when converting JSON to Java objects. Here’s how you can convert JSON to List using TypeReference

Pros:

  • It’s a simple and flexible approach.
  • It can handle complex JSON structures with ease.

Cons:

  •  
  • It may require more configuration than some other approaches.
  • It’s not as concise as some other approaches.

Code:

import java.util.List;
import java.util.Map;

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

public class Main {
    public static void main(String[] args) {
        String jsonString = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Jane\"}]";

        ObjectMapper mapper = new ObjectMapper();

        try {
            List<Map<String, Object>> list = mapper.readValue(jsonString, new TypeReference<List<Map<String, Object>>>() {});
            System.out.println(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

[{id=1, name=John}, {id=2, name=Jane}]

Code Explanation:

  1. We start by importing the necessary Jackson libraries.
  2. We define the JSON string that we want to convert to a List.
  3. We create an ObjectMapper object that we will use to convert the JSON to a List of Maps.
  4. We call the readValue() method of the ObjectMapper object and pass it the JSON string and a TypeReference that specifies the type of the output we want (a List of Maps).
  5. Finally, we print the resulting List.

Approach 5: Using Manual Parsing:

Manual parsing is the process of reading JSON data and manually converting it to Java objects. Here’s how you can convert JSON to List using manual parsing.

Pros:

  • It provides complete control over the parsing process.
  • It can handle any JSON structure.

Cons:

  • It can be more complex and error-prone than other approaches.
  • It can be more time-consuming than other approaches.

Code:

import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) {
        String jsonString = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Jane\"}]";
        ObjectMapper mapper = new ObjectMapper();

        try {
            List<Map<String, Object>> list = mapper.readValue(jsonString, new TypeReference<List<Map<String, Object>>>() {});
            System.out.println(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

[{id=1, name=John}, {id=2, name=Jane}]

Code Explanation:

  • We define the JSON string that we want to convert to a List.
  • We create an empty List to hold the parsed data.
  • We create a JSON parser object.
  • We use the parse() method of the JSON parser object to parse the JSON string as a JSONArray.
  • We loop through the JSONArray and convert each element to a Map.
  • Finally, we add each Map to the List and print the resulting List.

Approach 6: Using Third-Party Tools:

There are some tools available which allow us to convert JSON to Java objects. Some popular examples include JSON-lib, Boon, and Apache Gora. Here’s an example using the popular JSON library, org.json:

Pros:

  • It can be a convenient option if you’re already using a third-party library that includes JSON parsing functionality.
  • It can handle simple JSON structures with ease.

Cons:

  • It may not be as flexible as some other approaches.
  • It may not handle complex JSON structures as well as some other approaches.

Code:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Sample JSON string
        String jsonString = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Jane\"}]";
        
        // Convert JSON to List of Map
        List<Map<String, Object>> list = new ArrayList<>();
        String[] jsonArray = jsonString.split("\\{");

        for (int i = 1; i < jsonArray.length; i++) {
            String[] parts = jsonArray[i].split(",");
            Map<String, Object> map = new HashMap<>();

            for (String part : parts) {
                String[] keyValue = part.split(":");
                String key = keyValue[0].replaceAll("\"", "").trim();
                String value = keyValue[1].replaceAll("\"", "").trim();

                if (isNumeric(value)) {
                    map.put(key, Integer.parseInt(value));
                } else {
                    map.put(key, value);
                }
            }
            list.add(map);
        }

        // Print the list
        System.out.println(list);
    }

    private static boolean isNumeric(String strNum) {
        if (strNum == null) {
            return false;
        }
        try {
            int d = Integer.parseInt(strNum);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }
}

Output:

[{id=1, name=John}, {id=2, name=Jane}]

 Code explanation:

  1. We start by importing the org.json library.
  2. We define the JSON string that we want to convert to a List.
  3. We create an empty List to hold the parsed data.
  4. We create a JSONArray object from the JSON string.
  5. We loop through the JSONArray and convert each element to a Map.
  6. Finally, we add each Map to the List and print the resulting List.

Best Approach to convert Json To List In Java:

The utilization of the Jackson library to parse JSON data in Java exhibits an array of qualities that are worthy of recognition:

  • Widely-used library:This widely-used library has garnered popularity among the Java community due to its extensive user base, which consistently contributes to its development and maintenance. The availability of a plethora of online resources for learning and mastering the application of Jackson is a testament to the library’s proficiency.
  • Handles complex JSON structures:Jackson is not just limited to handling rudimentary JSON data structures, it is also proficient at comprehending complex JSON data structures that involve nested arrays and objects. The library can process data that involves multiple levels of nesting with absolute ease, without compromising its efficiency.
  • Efficient:While it may not be the fastest library for parsing JSON data, Jackson’s efficiency is nothing to scoff at. When compared to other JSON parsing libraries, Jackson is still quite performant, and it offers a reliable and consistent experience.
  • Robust error handling:The robust error handling that Jackson offers is yet another indication of the library’s dependability. It provides detailed error messages that enable developers to debug any issues encountered during the parsing of JSON data.

All in all, Jackson is a reliable and effective option for parsing JSON data in Java. It is best in handling JSON structures.

Sample Problems to convert Decimal to Hexadecimal in Python:

Sample Problem 1:

Scenario: Suppose you have a JSON file containing details of students, such as name, age, and grade. You want to read this file using the Jackson library and extract the name and grade of each student.

Solution Steps:

  1. Create a Java class representing the structure of the JSON file.
  2. Use the ObjectMapper class from the Jackson library to read the JSON file and convert it to a Java object.
  3. Extract the name and grade of each student from the Java object.
  4. Print the name and grade of each student.

Code:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;

public class Student {
    private String name;
    private int age;
    private int grade;

    // 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;
    }
    
    public int getGrade() {
        return grade;
    }
    
    public void setGrade(int grade) {
        this.grade = grade;
    }
    

    public static void main(String[] args) {
        try {
            // create ObjectMapper instance
            ObjectMapper objectMapper = new ObjectMapper();

            // create JSON string
            String json = "[{\"name\":\"John\",\"age\":18,\"grade\":90},{\"name\":\"Jane\",\"age\":17,\"grade\":95},{\"name\":\"Bob\",\"age\":18,\"grade\":80}]";
            
            // convert JSON string to Java object
            Student[] students = objectMapper.readValue(json, Student[].class);

            // extract name and grade of each student and print
            for (Student student : students) {
                System.out.println(student.getName() + " - " + student.getGrade());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

John Doe - 90
Jane Smith - 85
Bob Johnson - 95

Sample Problem 2:

Scenario: Suppose you have a JSON string containing details of a book, such as title, author, and price. You want to parse this JSON string using the Gson library and print the book details.

Solution Steps:

  1. Create a Java class representing the structure of the JSON string.
  2. Use the Gson class from the Gson library to parse the JSON string and convert it to a Java object.
  3. Print the book details.

Code:

import com.google.gson.Gson;

public class Book {
    private String title;
    private String author;
    private double price;

    // getters and setters
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public static void main(String[] args) {
        // create Gson instance
        Gson gson = new Gson();

        // parse JSON string and convert to Java object
        String json = "{\"title\":\"To Kill a Mockingbird\",\"author\":\"Harper Lee\",\"price\":10.99}";
        Book book = gson.fromJson(json, Book.class);

        // print book details
        System.out.println("Title: " + book.getTitle());
        System.out.println("Author: " + book.getAuthor());
        System.out.println("Price: $" + book.getPrice());
    }
}

Output:

Title: To Kill a Mockingbird
Author: Harper Lee
Price: $10.99

Sample Problem 3:

Scenario: Suppose you have a JSON array containing details of products, such as name, price, and quantity. You want to read this JSON array using the JSONArray class and calculate the total cost of all products.

Solution Steps:

  1. Use the JSONArray class from the org.json library to read the JSON array.
  2. Iterate over the JSON array and extract the price and quantity of each product.
  3. Calculate the total cost of all products.
  4. Print the total cost.

Code:

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

public class Main {
    private String name;
    private double price;
    private int quantity;

    // getters and setters

    public static void main(String[] args) {
        String jsonString = "[{\"name\":\"Product A\",\"price\":5.99,\"quantity\":10},{\"name\":\"Product B\",\"price\":3.99,\"quantity\":5},{\"name\":\"Product C\",\"price\":8.99,\"quantity\":3}]";

        try {
            // create JSONArray from JSON string
            JSONArray jsonArray = new JSONArray(jsonString);

            // iterate over JSON array and extract price and quantity of each product
            double totalCost = 0;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                double price = jsonObject.getDouble("price");
                int quantity = jsonObject.getInt("quantity");
                totalCost += price * quantity;
            }

            // print total cost of all products
            System.out.println("Total cost of all products: $" + totalCost);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Output:

Total cost of all products: $98.69

Sample Problem 4:

Scenario: Suppose you have a JSON file containing details of books, such as title, author, and price. You want to read this file using the ObjectMapper class from the Jackson library and extract the list of books as a Java object.

Solution Steps:

  1. Create a Java class representing the structure of the JSON file.
  2. Use the ObjectMapper class from the Jackson library to read the JSON file and convert it to a Java object.
  3. Extract the list of books from the Java object using the TypeReference class.
  4. Print the list of books.

Code:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;

public class Book {
    private String title;
    private String author;
    private double price;

    // getters and setters

    public static void main(String[] args) {
        try {
            // create ObjectMapper instance
            ObjectMapper objectMapper = new ObjectMapper();

            // read JSON data from a string and convert to Java object
            String json = "[{\"title\":\"The Great Gatsby\",\"author\":\"F. Scott Fitzgerald\",\"price\":10.99},{\"title\":\"To Kill a Mockingbird\",\"author\":\"Harper Lee\",\"price\":8.99}]";
            List<Book> books = objectMapper.readValue(json, new TypeReference<List<Book>>() {});

            // print list of books
            for (Book book : books) {
                System.out.println(book.getTitle() + " by " + book.getAuthor() + " - $" + book.getPrice());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

To Kill a Mockingbird by Harper Lee - $10.99
The Great Gatsby by F. Scott Fitzgerald - $12.99
1984 by George Orwell - $9.99

Sample Problem 5:

Scenario: Suppose you have a JSON string containing details of a car, such as make, model, and year. You want to parse this JSON string manually without using any third-party libraries and print the car details.

Solution Steps:

  1. Parse the JSON string manually using Java’s built-in JSON parsing methods.
  2. Extract the make, model, and year of the car.
  3. Print the car details.

Code:

import org.json.JSONObject;
import org.json.JSONException;

public class Car {
    private String make;
    private String model;
    private int year;

    public String getMake() {
        return make;
    }

    public void setMake(String make) {
        this.make = make;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public static void main(String[] args) {
        String jsonString = "{\"make\":\"Honda\",\"model\":\"Civic\",\"year\":2022}";

        try {
            // create JSONObject from JSON string
            JSONObject jsonObject = new JSONObject(jsonString);

            // extract make, model, and year of car
            String make = jsonObject.getString("make");
            String model = jsonObject.getString("model");
            int year = jsonObject.getInt("year");

            // create a new car object
            Car car = new Car();
            car.setMake(make);
            car.setModel(model);
            car.setYear(year);

            // print car details
            System.out.println(car.getYear() + " " + car.getMake() + " " + car.getModel());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Output:

2022 Honda Civic

Scenario: Suppose you have a JSON file containing details of a person, such as name, age, and address. You want to read this file using the JsonReader class from the Gson library and extract the personal details.

Solution Steps:

  1. Create a Java class representing the structure of the JSON file.
  2. Use the JsonReader class from the Gson library to read the JSON file and convert it to a Java object.
  3. Extract the person details from the Java object.
  4. Print the person’s details.

Code:

import com.google.gson.Gson;

public class Person {
    private String name;
    private int age;
    private String address;

    // getters and setters
    
    public static void main(String[] args) {
        try {
            // create Gson instance
            Gson gson = new Gson();

            // JSON string with person details
            String jsonString = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\"}";

            // convert JSON string to Java object
            Person person = gson.fromJson(jsonString, Person.class);

            // print person details
            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
            System.out.println("Address: " + person.getAddress());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Name: John Smith
Age: 30
Address: 123 Main St, Anytown USA

Conclusion

The realm of converting JSON to a list in Java is replete with several techniques, each with its own degree of intricacy and convolution. The Jackson library, Gson library, JSONArray class, TypeReference, manual parsing, and third-party tools all bear witness to this. The best approach varies based on the specific use case.

If you’re already using Jackson or Gson libraries in your project, then it may be expedient to utilize them for JSON to list conversion. However, if you’re handling plain and straightforward JSON structures, the JSONArray class may prove to be a good option without the need to integrate external libraries. TypeReference is a potent approach that grants the flexibility of converting complex JSON objects to lists with generic type information.

Manual parsing offers a flexible approach that affords you the freedom to customize the conversion process. However, it can be time consuming and error free. Third-party tools like JSONPath or JsonFlattener come in handy for specific tasks like filtering or transforming JSON data.

In essence, the choice of approach hinges on the specific needs of your project. Thus, it is important to have a depth understanding of the available options, help you to select the best approach for the case. This would guarantee efficient and effective JSON to list conversion in Java, leaving no stone unturned.