How To Convert String To Jsonarray In Java

JSON is a text-based data format for exchanging data over the internet. Converting a String representation of JSON data into a ‘JSONArray’ object is one of the common challenges.A JSONArray is a collection of JSON objects, which contain its own set of key-value pairs.

Example

[{"fruit":"apple ","cost":90},{"fruit":" orange","cost":70}]

It is a fundamental part of JSON used to represent a list of items such as products, events, or recipes and is widely used in modern web development.

In this blog post, we will discuss three approaches on how to convert a string into a jsonarray in java and explore why it is needed.

Why Is There A Need To Convert String To Jsonarray In Java?

Converting String to Jsonarray is necessary for several reasons.

Parsing JSON Data: If you have JSON data as a string, you need to parse it to access the values within it. Converting the String to JSON Array allows you to access individual values and parse the data.

Manipulating JSON Data: By using JSON Array we can easily manipulate the data by adding, removing, or sorting the element.

Data Visualization: Converting the String to a JSONArray can help you manipulate the data and display it in the UI in a readable format.

Approaches On How To Convert String to Jsonarray In Java:

There are several ways to convert String to Jsonarray in Java:

  1. Using the JSONArray constructor
  2. Using the JSONTokener class
  3. Using a GSON library

A Thorough Explanation Of Each Strategy About How To Convert String To Jsonarray In Java:

1. Using the JSONArray constructor:

The JSONArray constructor is the simplest and most straightforward method. It takes a string as its argument to convert the string to a JSONArray. The String should start and end with a square bracket.

Dependency:

<dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20230227</version>
</dependency>

Sample Code:

import org.json.JSONArray;
public class Main {
        public static void main(String[] args)   {
            String jsonString = "[{\"fruit\":\"apple \",\"cost\":90}, {\"fruit\":\" orange\",\"cost\":70}]";
            JSONArray jsonArray = new JSONArray(jsonString);

            System.out.println(jsonArray);
        }
    }

Output:

[{"fruit":"apple ","cost":90},{"fruit":" orange","cost":70}]

Code Explanation:

  1. Import the JSONArray class from the org.json package.
  2. Define a new class called Main with a main method.
  3. Create a string called jsonString that contains a JSON array.
  4. Using the JSONArray constructor, create a new JSONArray object called ‘productList’ that takes a string as its argument.
  5. Print the JSONArray object to the console.

2. Using the JSONTokener class:

The JSONTokener class is used to parse JSON text and create a corresponding JSON object array. It allows you to read a string of JSON data incrementally and construct a JSON object or array from it.

Dependency:

<dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20230227</version>
</dependency>

Sample Code:

import org.json.JSONArray;

import org.json.JSONTokener;

public class Main {
        public static void main(String[] args) {
            String jsonString = "[{\"Book\":\"A Place Called Home\",\"author\":\"Preeti Shenoy\"}, {\"Book\":\"The Maverick Effect\",\"author\":\"Harish Mehta\"}]";

            JSONArray jsonArray = new JSONArray(new JSONTokener(jsonString));

            System.out.println(jsonArray);
        }
    }

Output:

[{"Book":"A Place Called Home","author":"Preeti Shenoy"},{"Book":"The Maverick Effect","author":"Harish Mehta"}]

Code Explanation:

  1. The program imports the necessary classes from the org.json library.
  2. The JSON string to be converted to a JSONArray is defined as a string variable called jsonString.
  3. The JSONArray object is declared and initialized to null.
  4. A new JSONArray object is created using a JSONTokener object as an argument. The JSONTokener object is created using the jsonString variable.
  5. The System.out.println() statement is used to print the resulting JSONArray object.

3. Using a GSON library:

Gson is a third-party Java library used for converting Java objects to their JSON representation and vice versa, and it can also be used to convert a String to a JSONArray.

This can be done using the ‘fromJson()’ method, which takes a JSON string and converts it to JSONArray.

Dependency:

<dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.9</version>
</dependency>

Sample Code:

import com.google.gson.Gson;
import com.google.gson.JsonArray;
public class Main {
        public static void main(String[] args) {
            String jsonString = "[{\"Product\":\"TV \",\"Brand\":Samsung}, {\"Product\":\" Mobile\",\"Brand\":Apple}]";

            Gson gson = new Gson();
            JsonArray jsonArray = gson.fromJson(jsonString, JsonArray.class);

            System.out.println(jsonArray);
        }
    }

Output:

[{"Product":"TV ","Brand":"Samsung"},{"Product":" Mobile","Brand":"Apple"}]

Code Explanation:

  1. The code imports the Gson library and the JsonArray class.
  2. A string variable named jsonString is declared and initialized with a JSON array string.
  3. A Gson object is created.
  4. The fromJson() method of the Gson class is called with two parameters: the jsonString string and the JsonArray class.
  5. The fromJson() method converts the jsonString to a JsonArray object.
  6. The resulting JsonArray object is assigned to a variable named jsonArray.
  7. The code prints the resulting jsonArray object to the console.

Best Of The Three Methods:

For numerous reasons, the GSON library is regarded as the finest java method to turn a string into a JSONArray.

  1. High performance: As this method has high performance, it can handle large data sets effectively and can also support multithreading to further improve the processing speed of large data sets.
  1. Maintenance: Gson is regularly maintained and updated, which helps the developers use the latest technology available.
  1. Compatibility: The GSON library is compatible with a wide range of Java versions. It can also be integrated with various libraries and frameworks.
  1. Easy to use: Gson library is considered as one of the easiest method for converting Java objects to Json.It provides a wide range of options for serialization and deserialization process

Sample Problems For Converting String to JsonArray In Java:

Sample Problem 1:

A student wants to keep track of his upcoming exams. He has a list of exams with the exam name and dates. Write a java program that demonstrates how to change string to jsonarray in java and sort it according to the date.

Solution:

  1. Initialize a string variable with the list of exams containing their title and date
  2. Convert the string to a JSONArray using the JSONArray constructor
  3. Create an empty list of JSONObjects to store the sorted array elements
  4. Loop through the JSONArray and add each element to the list
  5. Sort the list of JSONObjects based on the ‘date’ field using a custom Comparator
  6. Reassign the sorted JSONObjects to the original JSONArray
  7. Print the sorted JSONArray using the toString() method

 Code:

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

public class Main {
    public static void main(String[] args)
    {
        String examList = "[{'title':'Java','date':'2023-01-01'},   " +
                                      "{'title':'Python','date':'2023-01-02'}," +
                                      "{'title':'AI','date':'2023-01-25'}]";

        JSONArray examArray = new JSONArray(examList);

        List<JSONObject> jsonList = new ArrayList<>();
        for (int j = 0; j < examArray.length(); j++) {
            jsonList.add(examArray.getJSONObject(j));
        }

        Collections.sort(jsonList, Comparator.comparing(obj -> obj.getString("date")));
        examArray = new JSONArray(jsonList);

        System.out.println(examArray.toString());
    }
}

Output:

[{"date":"2023-01-01","title":"Java"},{"date":"2023-01-02","title":"Python"},{"date":"2023-01-25","title":"AI"}]

Sample Problem 2:

A developer needs to build an e-commerce website that displays a list of products. They have a list of products with id, product name, and price. Write a java program that demonstrates how to change string to jsonarray in java using JSONTokener class and display products having a price below 20000 in jsonArray.

Solution:

  1. Create a JSON string that represents a list of products.
  2. Convert the string to a JSON array using JSONTokener.
  3. Create an empty JSON array to store the filtered products.
  4. Iterate through the products in the JSON array using a loop.
  5. Retrieve the price of each product using getDouble().
  6. Check if the price is below 20000.0.
  7. If the price is below the threshold, add the product to the filtered JSON array using put().
  8. Print the filtered JSON array.

 Code:

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class Main {
    public static void main(String[] args)    
    {



        String productList = "[{\"id\": 101, \"name\": \"Pen\", \"price\": 90.99}, " +
                             "{\"id\": 102, \"name\": \"Mobile\", \"price\": 50000.99}, " +
                             "{\"id\": 103, \"name\": \"watch\", \"price\": 15000.99}]";

        // Convert the string to a JSON array using JSONTokener
        JSONArray jsonArray = new JSONArray(new JSONTokener(productList));

        // Filter the products with a price below 20 and display them in the JSON array
        JSONArray filteredArray = new JSONArray();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject product = jsonArray.getJSONObject(i);
            double price = product.getDouble("price");
            if (price < 20000.0) {
                filteredArray.put(product);
            }
        }
        System.out.println(filteredArray);
    }
}

Output:

[{"price":10.99,"name":"Product A","id":1},{"price":15.99,"name":"Product C","id":3}]

Sample Problem 3:

Suppose you are building a website that allows customers to search a hotel having particular cuisine.You are having a list of hotels containing hotel name and cuisine. Write a java program that demonstrates how to convert string into jsonarray in java using gson library and list hotels having italian cuisine alone in JsonArray.

Solution:

  1. Create a JSON string with an array of objects.
  2. Create a Gson object.
  3. Convert the JSON string to a JsonArray using the fromJson method of the Gson object.
  4. Create a new JsonArray to store hotels with Italian cuisine.
  5. Iterate through the JsonArray to find hotels with Italian cuisine.
  6. If a hotel has Italian cuisine, add it to the italianHotels JsonArray.
  7. Finally, print the hotels with Italian cuisine.

 Code:

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class Main {
        public static void main(String[] args) {
                    String jsonStr = "[{'name':'Hotel A','cuisine':'Italian'},{'name':'Hotel B','cuisine':'Chinese'},{'name':'Hotel C','cuisine':'Italian'}]";

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

                    // Convert the JSON string to a JsonArray
                    JsonArray jsonArray = gson.fromJson(jsonStr, JsonArray.class);

                    // Create a new JsonArray to store hotels with Italian cuisine
                    JsonArray italianHotels = new JsonArray();

                    // Iterate through the JsonArray to find hotels with Italian cuisine
                    for (JsonElement element : jsonArray) {
                        JsonObject obj = element.getAsJsonObject();
                        String cuisine = obj.get("cuisine").getAsString();
                        if (cuisine.equals("Italian")) {
                            italianHotels.add(obj);
                        }
                    }

                    // Print the hotels with Italian cuisine
                    System.out.println(italianHotels.toString());
                }
            }

Output:

[{"name":"Hotel A","cuisine":"Italian"},{"name":"Hotel C","cuisine":"Italian"}]

Conclusion:

JSON arrays can certainly be useful for manipulating data and exchanging data between systems in web development; therefore, in certain scenarios, programmers have to convert a string to a json array.

We have discussed three methods for converting strings to JSON arrays. Among them, the GSON method is considered the best method due to its flexibility and advanced features.

However, other two methods can be effective in certain use cases. Understanding the methods properly helps to find the method that is apt for the particular use case.