How To Convert JsonObject To JsonString In Java

JSON which stands for Javascript Object Notation, used to exchange data between a server and a client is a lightweight data interchange format. It’s becoming a popular choice for APIs due to its simplicity, flexibility, and interaction with different languages.

A JSONObject, which is a collection of key value pairs, is the representation of JSON data in java. When transmitting data over the network it becomes necessary to convert it into string format which can be easily parsed and transferred, to do so JSON serialisation concept is used.

Why there is need to convert jsonobject to jsonstring in java?

In java, there can be multiple reasons for why it becomes necessary to convert JSONObject to JSONString. Following are some of the reasons:

  • Data transmission: JSON strings are commonly used for transmitting data over the network. It becomes easier to transfer the data over the network to a remote server or a client by converting a JSONObject to a JSON string which makes the process more efficient.
  • Data storage: JSON strings are also used for storing data in databases or files. It becomes possible to store data in a file or a database and later retrieve it by parsing the JSON string for further manipulation by converting a JSONObject to a JSON string.
  • Interoperability: Since JSON is a language-independent format, numerous programming languages can easily comprehend it. Our Java programme can communicate with other JSON-using applications by transforming a JSONObject to a JSON string.
  • Parsing: JSON strings are easier to parse than JSON objects. Simplification of parsing process, making it easier to extract the necessary data from the JSON string is possible by converting a JSONObject to a JSON string.
  • Debugging: JSON strings are easier to read and understand than JSON objects. Debugging and troubleshooting one’s application can be done easily by examining the JSON string after converting it from JSONObject.

Different methods to convert jsonobject to jsonstring

  1. Using the toString() method.
  2. Using the write() method.
  3. Using the ObjectMapper() class.

Detailed Explanation:

1. Using the toString() method

Using the toString() method on the JSONObject object is the easiest way to convert a JSONObject to a JSON string. This approach returns the new JSON string which showcases the value of the JSONObject.

Sample Code:

import org.json.JSONObject;

public class JSONObjectToJsonStringExample {
    public static void main(String[] args) {
        // create a new JSONObject
        JSONObject jsonObject = new JSONObject();
        
        // add some key-value pairs to the JSONObject
        jsonObject.put("name", "John Doe");
        jsonObject.put("age", 30);
        jsonObject.put("email", "[email protected]");
        
        // convert the JSONObject to a JSON string
        String jsonString = jsonObject.toString();
        
        // print the JSON string to the console
        System.out.println(jsonString);
    }
}

Output:

{"name":"John Doe","age":30,"email":"[email protected]"}

Code Explanation:

  1. We can get a JSON string representation of the corresponding JSONObject  by applying the built in toString() method of the JSONObject class.
  2. JSON java library provides the JSONObject class which is a sub module which includes a set of classes which will be helpful when working with JSON data in java.
  3. A new JSONObject is created and some data is added to it using the built in put() method.
  4. To get the JSON string representation of the corresponding JSONObject call built in toString() method.
  5. The output of the previous step, that is JSON string representation, is further stored in a variable for further processing and analysis of data in the program.
  6. Finally the JSON string representation is displayed on the console using println() method.

Note : In order to run all these codes the user must import all the required files.

2.Using the write() method

The JSONObject class provides a write() method that writes the JSON string to a Writer object.

Sample Code:

import org.json.JSONObject;
import java.io.FileWriter;
import java.io.IOException;

public class JSONObjectToJsonStringExample {
    public static void main(String[] args) {
        // create a new JSONObject
        JSONObject jsonObject = new JSONObject();
        
        // add some key-value pairs to the JSONObject
        jsonObject.put("name", "John Doe");
        jsonObject.put("age", 30);
        jsonObject.put("email", "[email protected]");
        
        // write the JSONObject to a file
        try (FileWriter file = new FileWriter("data.json")) {
            jsonObject.write(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

{"name":"John Doe","age":30,"email":"[email protected]"}

Code Explanation:

  1. The write() method is another built-in method of the JSONObject class that writes the JSON string to a Writer object.
  2. Any sort of Writer object, such as a StringWriter object that writes the JSON string to a string buffer, is a Writer object, and it can write the JSON string to a file or any other type of Writer object.
  3. The put() method is used in this example to add some data to a newly created JSONObject object.
  4. FileWriter object is created and file name is passed to it as a parameter.
  5. We then call the write() method on the JSONObject object, passing the FileWriter object as a parameter.
  6. This writes the JSON string to the file specified by the FileWriter object.
  7. If there is an exception while writing to the file, we catch it and print the stack trace using the e.printStackTrace() method.

3.Using the ObjectMapper class

The ObjectMapper class from the Jackson library can be used to convert a JSONObject to a JSON string. Better performance and flexibility is provided by this method as compared to other methods.

Sample Code:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONObject;

public class JSONObjectToJsonStringExample {
    public static void main(String[] args) throws JsonProcessingException {
        // create a new JSONObject
        JSONObject jsonObject = new JSONObject();
        
        // add some key-value pairs to the JSONObject
        jsonObject.put("name", "John Doe");
        jsonObject.put("age", 30);
        jsonObject.put("email", "[email protected]");

        // create a new ObjectMapper instance
        ObjectMapper objectMapper = new ObjectMapper();
        
        // convert the JSONObject to a JSON string using the ObjectMapper
        String jsonString = objectMapper.writeValueAsString(jsonObject);

        // print the JSON string to the console
        System.out.println(jsonString);
    }
}

Output:

{"name":"John Doe","age":30,"email":"[email protected]"}

Code Explanation:

  1. The ObjectMapper class is part of the Jackson library, which is a popular JSON parsing library for Java.
  2. This class provides methods for converting between JSON strings and Java objects, including JSON objects and arrays.
  3. In this example, we create a new JSONObject object and add some data to it using the put() method.
  4. We then create an instance of the ObjectMapper class, which we can use to convert the JSONObject object to a JSON string.
  5. We call the writeValueAsString() method on the ObjectMapper object, passing the JSONObject object as a parameter.
  6. This method returns the JSON string representation of the JSONObject object.
  7. A variable is created and used to store the generated JSON string, which may then be utilised for additional processing or written to a file.
  8. In this example, we use the println() method to print the JSON string to the console.

Best out of three methods

ObjectMapper class is generally considered the best method for converting a JSONObject to a JSON string in Java:

  1. The ObjectMapper class is part of the Jackson library, which is a widely-used JSON parsing library for Java.It is an established, well-documented library with a sizable user base that has been around for a long time.
  2. The ObjectMapper class has more sophisticated functionality than the other methods, including support for many more data formats in addition to JSON, custom serialisation and deserialization, and handling of complex JSON structures.
  3. The extremely versatile ObjectMapper class can be tailored to meet the unique requirements of your application. For example, you can configure it to ignore null values, use custom field names, or format dates in a specific way.
  4. The ObjectMapper class provides better performance than the other methods, especially when working with large or complex JSON data.It makes use of a streaming API to prevent memory bottlenecks caused by apps that load the complete JSON string into memory at once.

Generally, when dealing with vast or sophisticated JSON data, the ObjectMapper class is the best way to translate a JSONObject into a JSON string in Java.But, the approach you choose will ultimately depend on the particular needs of your application. It is usually a good idea to weigh the advantages and disadvantages of each method before making a choice.

Sample Problems

Sample Problem 1

Make a Java program that receives a JSONObject from one file, converts it to a JSON string, and then writes the final JSON string to a different ducument. Use the org.json library for JSON conversion. Print the JSON string to the console after conversion.

Solution:

  1. The program starts by defining two file paths: ‘inputFile’ and ‘outputFile’. These are the paths to the input and output files that will be used for the program.
  2. The program reads the input JSON object from the ‘inputFile’ using the ‘FileReader’ class and the ‘JSONTokener’ class from the ‘org.json’ library. The ‘JSONTokener’ class is used to parse the JSON object from the input file into a ‘JSONObject’ object.
  3. The program converts the ‘JSONObject’ object to a JSON string using the toString() method of the ‘JSONObject’ class.
  4. The program writes the JSON string to the ‘outputFile’ using the ‘FileWriter’ class.
  5. The program prints the JSON string to the console using the System.out.println() method.
  6. In case of any exceptions thrown by the code, such as a ‘JSONException’ or an ‘IOException’, the program handles them by printing the stack trace to the console.

Code:

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

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ConvertJSONObjectToString {
    public static void main(String[] args) {
        // input and output file paths
        String inputFile = "input.json";
        String outputFile = "output.json";

        // read JSONObject from file
        JSONObject jsonObject = null;
        try (FileReader fileReader = new FileReader(inputFile)) {
            JSONTokener jsonTokener = new JSONTokener(fileReader);
            jsonObject = new JSONObject(jsonTokener);
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }

        // convert JSONObject to JSON string
        String jsonString = jsonObject.toString();

        // write JSON string to file
        try (FileWriter fileWriter = new FileWriter(outputFile)) {
            fileWriter.write(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // print JSON string to console
        System.out.println(jsonString);
    }
}

Input:

{
    "name": "John",
    "age": 30,
    "city": "New York"
}

Output:

{"name":"John","age":30,"city":"New York"}

Sample Problem 2

Create a JSONObject with some key-value pairs and turn it into a structured JSON string with line breaks by writing a Java programme. The write() method should then be used to write the JSON string to a file. After conversion, print the converted JSON string to the console.

Solution:

  1. Using the import keyword, we first import the required classes from the java.io and org.json packages.
  2. Next, we define the ConvertJSONObjectToString class that contains the main() method.
  3. Inside the main() method, we create a new JSONObject object called jsonObject using the default constructor.
  4. Then, we add some key-value pairs to the jsonObject using the put() method.
  5. After that, we convert the jsonObject to a formatted JSON string with an indentation factor of 4 spaces using the toString(int indentFactor) method of the JSONObject class.
  6. The FileWriter class’s write() method is then used to write the JSON string to a file called “output.json.”. We use a try-with-resources statement to automatically close the FileWriter after writing to the file.
  7. Lastly, we use the System.out.println() function to print the JSON string to the console.

Code:

import org.json.JSONObject;

import java.io.FileWriter;
import java.io.IOException;

public class ConvertJSONObjectToString {
    public static void main(String[] args) {
        // create a JSONObject with some key-value pairs
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "John");
        jsonObject.put("age", 30);
        jsonObject.put("city", "New York");

        // convert JSONObject to formatted JSON string with indentation and line breaks
        String jsonString = jsonObject.toString(4);

        // write JSON string to file
        try (FileWriter fileWriter = new FileWriter("output.json")) {
            fileWriter.write(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // print JSON string to console
        System.out.println(jsonString);
    }
}

Output:

{
    "name": "John",
    "age": 30,
    "city": "New York"
}

Sample Problem 3

Create a Java object with some attributes and values in a Java programme, and then use the ObjectMapper class to convert it to a JSON string. The writeValue() function of the ObjectMapper class should then be used to write the JSON string to a file. After conversion, print the converted JSON string to the console.

Solution:

  1. First, a Java object called Person is created, and its name and age fields have the values “John Doe” and 30, respectively, set.
  2. The ObjectMapper class from the Jackson library is used to convert the Java object to a JSON string using the writeValueAsString() method. The resulting JSON string is stored in a variable named jsonString.
  3. A File object is created with the file name “person.json”.
  4. The JSON string is written to the file created in the previous step using the ObjectMapper class’ writeValue() method.
  5. Using the System.out.println() function, the programme prints the JSON string to the console.

Code:

import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JavaObjectToJsonFileExample {

    public static void main(String[] args) throws Exception {
        // Create a Java object with some fields and values
        Person person = new Person("John Doe", 30);

        // Convert the Java object to a JSON string
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(person);

        // Write the JSON string to a file
        File file = new File("person.json");
        objectMapper.writeValue(file, person);

        // Print the JSON string to the console
        System.out.println(jsonString);
    }

    private static class Person {
        private String name;
        private int age;

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

        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;
        }
    }
}

Output:

{"name":"John Doe","age":30}

Conclusion

To summarize, converting a JSONObject to a JSON string in Java is a fundamental operation when working with JSON data. The function toString() { [native code] }(), toJSONString(), and write() methods are just a few of the tools available to Java developers to complete this task. It allows for the transfer and storage of data in a standardised format.

The best technique depends on the particular use case and has its own benefits and drawbacks. Developers can streamline the parsing and manipulation of JSON data in their Java programmes by utilising the org.json library, making it simpler to work with data from various sources and platforms.