How To Convert Json Object To String In Java

JSON (JavaScript Object Notation) is a popular data interchange format that is widely used in web applications. In Java, working with JSON objects is a common task, and there are various scenarios where it becomes necessary to convert a JSON object to a string. This can be particularly useful when sending data over the network or storing it in a database.

There are several libraries available in Java that provide efficient and optimised methods for converting JSON objects to strings.

In this article, we will explore different approaches for converting a JSON object to a string in Java.


Need for Converting JSON Object To String In Java

Converting a JSON object to a string in Java is necessary for various reasons such as:

  • Sending JSON data over the network: When sending JSON data over the network, it is required to convert a JSON object to a string before transmitting it.
  • Storing JSON data in a database: Many databases support the storage of JSON data as strings. Therefore, it is necessary to convert a JSON object to a string before storing it in a database.
  • Debugging JSON data: In order to debug JSON data, it is necessary to convert the JSON object to a string for printing or logging.
  • Displaying JSON data: Many front-end frameworks require JSON data in string format to display it in a readable form on the user interface.
  • Interoperability: When integrating with third-party applications, it is essential to convert a JSON object to a string to ensure interoperability.

Different Approaches on for converting json object to string

There are various approaches to converting a JSON object to a string in Java. Here are some of the commonly used ones:

  1. Using the JSON libraries: The most common approach is to use third-party libraries such as Jackson, Gson, or JSON.simple. These libraries provide simple and efficient methods to convert JSON objects to strings and vice versa.
  2. Manually creating a string: Another approach is to manually create a string from a JSON object by iterating over its key-value pairs and constructing a string with the appropriate syntax. This approach is more time-consuming and error-prone but may be useful in specific scenarios.

Approach 1: Using the JSON libraries

This approach involves using a third-party JSON library to convert a JSON object to a string.

The library provides methods to serialize the JSON object to a string. The library methods may differ based on the library used.

Example Code using Jackson Library:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import java.io.IOException;
import java.io.StringWriter;

public class JsonToStringExample1 {
    public static void main(String[] args) throws IOException {
        // create a JSON object
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter writer = mapper.writer();
        Object jsonObj = mapper.readValue("{\"name\":\"Mike\", \"age\":40}", Object.class);
        
        // convert the JSON object to a string
        StringWriter stringWriter = new StringWriter();
        writer.writeValue(stringWriter, jsonObj);
        String jsonString = stringWriter.toString();

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

Output:

{"name":"Mike","age":40}

Explanation:

  • Create a new ObjectMapper object from the Jackson library.
  • Create a StringWriter object, which is a character stream that collects its output in a string buffer.
  • Call the writeValue method of the ObjectMapper object to convert the JSON object to a string and writes the result to the StringWriter object.
  • Retrieve the resulting string from the StringWriter object using its toString method.

Approach 2:  Manually creating a string

This approach involves manually iterating over the JSON object to construct a string.

The object is iterated over in a specific order and the values are concatenated to form a string.

Example Code:

import org.json.JSONObject;

import java.util.Iterator;

public class JsonToStringExample2 {
    public static void main(String[] args) {
        // create a JSON object
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("name", "Mike");
        jsonObj.put("age", 40);
        
        // convert the JSON object to a string
        StringBuilder stringBuilder = new StringBuilder("{");
        Iterator<String> keys = jsonObj.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            stringBuilder.append("\"").append(key).append("\":\"").append(jsonObj.get(key)).append("\"");
            if (keys.hasNext()) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("}");
        String jsonString = stringBuilder.toString();
        
        // print the resulting string to the console
        System.out.println(jsonString);
    }
}

Output:

{"name":"Mike","age":40}

Explanation:

  • Initialises a StringBuilder object, which is a mutable sequence of characters.
  • Calls the append method of the StringBuilder object to add an opening curly brace to the string.
  • Initialises a Set object containing the keys of the JSON object.
  • Uses a for-each loop to iterate over the keys in the Set object.
  • Inside the loop, it calls the append method of the StringBuilder object to add the key and its value to the string.
  • Adds a comma separator to the string, except for the last key-value pair.
  • Adds a closing curly brace to the string.

Note: You will need to have the Jackson library (for Approach 1) and the JSON library (for Approach 2) in your classpath in order to run these examples.

Best Approach for “how to convert json object to string in java”

Using a JSON library is the best approach for converting JSON objects to strings in Java for the following reasons:

  •  Optimised and efficient: These libraries provide efficient and optimised methods for converting JSON objects to strings.
  • Avoid Errors: Manually creating a string from a JSON object can be a tedious and error-prone process, especially for complex JSON structures.
  • Extra features: Jackson is a popular and widely used library that offers many features beyond just converting JSON objects to strings, including data binding and tree model parsing.
  • Easy and lightweight: Gson is another popular JSON library that provides a simple and intuitive API for working with JSON objects in Java.

On the other hand, JSON.simple is a lightweight and easy-to-use library that provides basic functionality for working with JSON data.

Sample Problems

Sample Problem 1:  Using the JSON libraries

Suppose you are building a website for an e-commerce store that sells a variety of products. You need to keep track of the orders placed by customers, which will be stored in a complex JSON object. You want to convert this JSON object to a string for easier storage and retrieval. You can use the Jackson Library to convert the JSON object to a string. The JSON object includes the customer’s name, age, city, hobbies, and address. The hobbies array contains the name and duration of each hobby, while the address object includes the street name and zip code.
Input JSON:

{\”name\”:\”John Doe\”,\”age\”:30,\”city\”:\”New York\”,\”hobbies\”:[{\”name\”:\”reading\”,\”duration\”:120},{\”name\”:\”running\”,\”duration\”:60}],\”address\”:{\”street\”:\”123 Main St\”,\”zipcode\”:\”10001\”}}

  • The JSON object to be converted is stored in a JSONObject variable named jsonObj.
  • The code uses Approach 1 to convert the JSON object to a string.
  • The resulting string is stored in a String variable named jsonString.
  • The code then prints the resulting string to the console.
// Importing required libraries
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class JsonToStringExample {
    public static void main(String[] args) throws IOException {
        // Creating a complex JSON object
        String jsonString = "{\"name\":\"John Doe\",\"age\":30,\"city\":\"New York\",\"hobbies\":[{\"name\":\"reading\",\"duration\":120},{\"name\":\"running\",\"duration\":60}],\"address\":{\"street\":\"123 Main St\",\"zipcode\":\"10001\"}}";

        // Converting JSON object to string using Jackson Library
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonToString = objectMapper.writeValueAsString(jsonString);

        // Output
        System.out.println(jsonToString);
    }
}

Output:

"{\"name\":\"John Doe\",\"age\":30,\"city\":\"New York\",\"hobbies\":[{\"name\":\"reading\",\"duration\":120},{\"name\":\"running\",\"duration\":60}],\"address\":{\"street\":\"123 Main St\",\"zipcode\":\"10001\"}}"

Sample Problem 2: Manually creating a string

Suppose you are working on a project where you need to extract information from a JSON file and save it as a string. You are not allowed to use any external libraries, so you need to write a code that can convert a JSON object to a string manually.

Input JSON: {\”name\”:\”Jane Doe\”,\”age\”:20,\”city\”:\”New York\”}
Solution:

  • The JSON object to be converted is stored in a JSONObject variable named jsonObj.
  • The resulting string is stored in a String variable named jsonString.
  • The code then prints the resulting string to the console.
import org.json.JSONObject;
import java.util.Map;

public class JsonToStringExample2 {
    public static void main(String[] args) {
        // Creating a JSON object
        String jsonString = "{\"name\":\"Jane Doe\",\"age\":20,\"city\":\"New York\"}";

        // Converting JSON object to string manually
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{");
        for (Map.Entry<String, Object> entry : new JSONObject(jsonString).entrySet()) {
            stringBuilder.append("\"" + entry.getKey() + "\"" + ":");
            stringBuilder.append("\"" + entry.getValue() + "\"" + ",");
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        stringBuilder.append("}");
        String jsonToString = stringBuilder.toString();

        // Output
        System.out.println(jsonToString);
    }
}

Output:

{"name":"Jane Doe","age":20,"city":"New York"}


Conclusion on how to convert json object to string in java

In conclusion, converting a JSON object to a string in Java is a crucial task in many modern applications that deal with data interchange.

There are several ways to achieve this conversion, but using a JSON library such as Jackson, Gson, or JSON.simple is the most efficient and reliable approach. These libraries provide optimized methods that make the conversion process straightforward and easy to implement, and also handle any necessary error checking.

The choice of approach should depend on the complexity of the object, performance requirements, and integration with other libraries.