How To Convert Json Array To String In Java

Web services and APIs frequently employ the popular data exchange format JSON (JavaScript Object Notation). The effective way to represent JSON in java is a JSON array which is a collection of JSON objects.

The need to convert a JSON array to a string may be necessary in some cases as per problem’s requirements, even though JSON arrays are excellent for describing data.

By the end of this blog, one will be able to understand the concept of conversion of JSON array to string in java.

Necessity to convert a JSON array to a string?

In java, There can be multiple instances where there will be a need to convert a JSON array to string for the sake of the program. Following are some of the reasons for conversion:

  • Sending JSON data over a network: It becomes necessary to convert JSON data to string first whenever one is going to send it over a network. The reason to do so is network protocols usually deals with text based data, and JSON is a text based format. So conversion of JSON array to string ensures that it can be sent over the network.
  • Keeping JSON data in a database: MongoDB is one database that keeps JSON data. Before putting the JSON array in the database, you might need to convert it to a string in several circumstances.
  • Logging JSON data: If you report JSON data as a string while logging it then it can be read and examined with ease.
  • Testing JSON data: Comparing JSON strings rather than JSON objects directly may be simpler when testing an application that consumes or produces JSON data.

It becomes crucial in a number of situations while dealing with data, which includes sending data over a network, saving data in a database for analysis, logging data for reference and testing software.

Best Way to convert json array to string in java

As discussed above about the importance of converting json array to string in java there is a crucial component i.e. org.json.JSONArray library which is necessary to import in the file before coding which is necessary to convert json array to string in java.

We will understand this with sample code and its explanation:

Code:

import org.json.JSONArray;

public class JsonArrayToStringExample {
    public static void main(String[] args) {
        // create a JSON array with some values
        JSONArray jsonArray = new JSONArray();
        jsonArray.put("value1");
        jsonArray.put("value2");
        jsonArray.put("value3");

        // convert the JSON array to a string
        String jsonString = jsonArray.toString();

        // print the resulting string
        System.out.println(jsonString);
    }
}

Output:

["value1","value2","value3"]

Explanation:

  1. We import the JSONArray class from the org.json package.
  2. We define a class called JsonArrayToStringExample.
  3. The main method of program is defined as a entry/ start point for program
  4. New JSONArray object is created inside the main method and some values are added into it using the put method.
  5. We convert the JSONArray to a string using the toString method.
  6. We store the resulting string in a variable called jsonString.
  7. We print the jsonString variable to the console using the println method.

The contents of the original JSON array is represented using the above JSON formatted string.

Sample Problem

Sample Problem 1

Write a code in Java program that reads a JSON array from any given file, then from the file user has to manipulate the data. Now after manipulating the user has to convert the array to a string.

Solution:

  1. We import the necessary classes from the java.io and org.json packages.
  2. We define a class called JsonArrayExample.
  3. The main method of the program is defined as an entry/ start point for the program.
  4. Inside the main method, we read the contents of a JSON file named data.json into a string using the Files.readAllBytes method.
  5. We create a JSONArray object from the string using the JSONArray constructor.
  6. We iterate over the elements in the array using a for loop.
  7. Using the getString method of the JSONObject class we get the value of the name field as a string for each element.
  8. Using the toUpperCase method of the string class, the name is converted to uppercase.
  9. We set the new value of the “name” field using the put method of the JSONObject class.
  10. After modifying all the elements, we convert the modified JSONArray to a string using the toString method.
  11. We write the modified string back to a new file named modified_data.json using the Files.write method.
  12. We catch any IOException or JSONException that may occur and print an error message

Code:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonArrayExample {
    public static void main(String[] args) {
        try {
            // read the contents of the JSON file into a string
            String jsonString = new String(Files.readAllBytes(new File("data.json").toPath()));

            // create a JSONArray object from the string
            JSONArray jsonArray = new JSONArray(jsonString);

            // iterate over the elements in the array and modify them
            for (int i = 0; i < jsonArray.length(); i++) {
                // get the current element as a JSONObject
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                // get the value of the "name" field and convert it to uppercase
                String name = jsonObject.getString("name").toUpperCase();

                // set the new value of the "name" field
                jsonObject.put("name", name);
            }

            // convert the modified JSONArray to a string
            String modifiedJsonString = jsonArray.toString();

            // write the modified string back to the file
            Files.write(new File("modified_data.json").toPath(), modifiedJsonString.getBytes());
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        } catch (JSONException e) {
            System.out.println("Error parsing JSON: " + e.getMessage());
        }
    }
}

data.json file:

[
  {
    "name": "Alice",
    "age": 25
  },
  {
    "name": "Bob",
    "age": 30
  },
  {
    "name": "Charlie",
    "age": 35
  }
]

When the JsonArrayExample program is run with this data.json file, it should modify the name field of each element to be uppercase and write the following JSON-formatted string to a new file called modified_data.json:

Output:

[{"name":"ALICE","age":25},{"name":"BOB","age":30},{"name":"CHARLIE","age":35}]

The program should not output anything to the console if it runs successfully.

The program will display error messages to the console, if the compiler encounters any errors reading the file or parsing the JSON file.

Advantages

The following are some benefits of converting a JSON array to a string in Java:

  • Simpler data manipulation: It is simple to manipulate data after converting a JSON array to a string with Java’s built in string manipulation capabilities. This can be very helpful since it makes it possible to handle and manipulate data effectively, when working with large JSON data sets.
  • Easy data transmission: Converting a JSON array to a string is a common requirement when transmitting JSON data over the internet or between different systems. By converting the data to a string, it can be easily transmitted using standard HTTP protocols or other network communication protocols.
  • Better performance: Compared to working with the JSON data directly, better performance is provided when working with data after converting the JSON array to a string. The reason is string manipulation functions are generally faster and more efficient than working with JSON objects and arrays.
  • Improved readability: When dealing with intricate JSON structures, converting a JSON array to a string might make data easier to interpret. The data can be quickly seen and examined using common text editors and other tools by being converted to a string.

In general, a number of advantages are provided which can make working with JSON data easier, more efficient and more effective after converting it into string in java.

Conclusion

To conclude, the process of converting a JSON array to a string in Java includes reading the JSON data into a JSONArray object, manipulating the data as per the requirement of the program for better usage and efficiency and then conversion of the manipulated JSONArray back to a string.

All of this is achievable with the help of the org.json library, which provides the multiple easy to use classes for the purpose of parsing and manipulation of JSON data.

Note: code and sample code in this blog need some conditions before running, first of all gradle should be built, some dependencies are to be changed as external library org.json is used, downloading of jar files are necessary and it is required to add jar files through references.

Lastly external files are not provided such as data.json, so code will not run directly until all the above conditions are met.