How To Convert Json String To Json Object In Java

JSON (JavaScript Object Notation) has become a well-liked data transfer standard in modern software development because of its simplicity, flexibility, and use.

Although JSON strings are typically used to accept Input data in Java programming, there may be times when a different JSON string format is required for processing or data transmission. It could be essential to change the original JSON data’s structure or content when converting a JSON string to another JSON string format.Java offers a number of solutions for this.

This technical blog will delve into the different approaches to learn how to convert json string to json object in java, providing detailed code examples and in-depth explanations for each method.

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

For a variety of causes, Java programmers may have to convert a JSON text into a JSON object. They include, among others:

  • JSON objects are easier to utilise than JSON strings for the data administration and querying.
  • Java’s ease of serialisation and deserialization makes JSON objects a more effective and practical data format for data sharing.
  • The easiest solution with which JSON objects can be changed to Java objects / classes makes working with JSON data in object-oriented programming way much easier.
  • JSON objects can be easily manipulated and modified, making them a more versatile data format for dynamic applications and systems.
  • For data analysis and visualisation, JSON objects are advantageous since they can be quickly searched for and filtered depending on their properties.

Developers may take use of these advantages and work with JSON data in their Java programmes more hastily and effectively by converting a JSON string to a JSON object.

Different methods to convert jsonobject to jsonstring in java

These are the methods that answer the question how to convert json string to json object in java.

  1. Using the JSONObject class from the JSON library
  2. Using the Jackson library’s ObjectMapper class
  3. Using the Gson library’s JsonParser class
  4. Using the org.json.simple library’s JSONValue class

Detailed Explanation:

1. Using the JSONObject class from JSON library

This method involves creating a new JSONObject object and passing the JSON string as a parameter to its constructor.  The JSON library gives an easy way to work with JSON data in Java.

Sample Code:

import org.json.*;

public class JsonExample {
    public static void main( String[] argu ) {
        // JSON string
        String st1 = "{\"nam\":\"Jason\", \"Age\":29, \"Lives\":\"New Jersey\"}";

        // Creating a JSONObject instance from the JSON string
        JSONObject jsonObject = new JSONObject(st1);

        // Retrieving values from the JSON object using the get() method
        String num = jsonObject.getString("nam");
        int umr = jsonObject.getInt("Age");
        String lives = jsonObject.getString("Lives");
{"city":"New York","name":"John","age":30}// Printing the values retrieved from the JSON object
        System.out.println( "Name_: " + num);
        System.out.println( "Age: " + umr);
        System.out.println( "Lives: " + lives);
    }
}

Output:

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

Note : In order to run the code all the object libraries must be installed in the user system first.

Code Explanation:

  1. The code begins with importing the JSONObject class from the org.json package. This class provides methods to work with JSON data.
  2. We then create a new JSONObject instance named jsonObject using the no-argument constructor. This creates an empty JSON object.
  3. Using the put() method of the JSONObject class, we can add key-value pairs to the jsonObject in code. In this example, we add three key-value pairs with the values “num,” “age,” and “city” being “Jason,” 29, and respectively.
  4. Finally, we print the jsonObject using the System.out.println() method. To render the jsonObject as a string, the function toString() { [native code] }() function of the JSONObject class is used internally.The output will be jsonObject is basically a string representation of a JSON object.

2. Using the Jackson library’s ObjectMapper class

This method involves creating a new ObjectMapper object and calling its readValue() method to parse the JSON string into a Java object. The Jackson library is a popular choice for working with JSON data in Java.

Sample Code:

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


public class JsonExample {
    public static void main(String[] args) {
        // JSON string
        String json_String = "{\"name\":\"joshua\", \"age\":28, \"city\":\"New Jersey\"}";

        // Creating an instance of the ObjectMapper class
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // Converting the JSON string to a JSON object
            Object json_Object = objectMapper.readValue(json_String, Object.class);

            // Printing the JSON object
            System.out.println(json_Object);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

{city=New Jersey, name=Joshua, age=28}

Code Explanation:

  1. The ObjectMapper class is first loaded from the com.fasterxml.jackson.databind package. Methods to read and write JSON data are offered by this class.
  2. The IOException class from the java.io library is also loaded. While reading or writing JSON data, this class is used to handle I/O exceptions that may arise.
  3. After that, a main() function is added to the JsonExample class.
  4. A JSON string called jsonString is created in the main() method and includes a straightforward JSON object with the three fields name, age, and city.
  5. We create a new instance of the objectMapper class. Methods to read and write JSON data are given by this class.
  6. The JSON string is then converted into a JSON object through using ObjectMapper class’s readValue() function. The Object class and the JSON string are passed as parameters to this method. The JSON object’s type is automatically determined by the ObjectMapper class, which further converts it to the correct Java object.
  7. To handle any IOException that may occur when reading the JSON data, we surround the readValue() method in a try-catch block.
  8. At last, we just use System.out.println() method to print the JSON object. A string representation of the JSON object is what the JSON object outputs.

3. Using the Gson library’s JsonParser class

This method involves making a new JsonParser object and awaking its parse() technique to parse the JSON string into a JsonElement object.

Sample Code:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class JsonExample {
    public static void main(String[] args) {
        // JSON string
        String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";

        // Creating an instance of the JsonParser class
        JsonParser jsonParser = new JsonParser();

        // Parsing the JSON string to a JsonObject
        JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();

        // Printing the JsonObject
        System.out.println(jsonObject);
    }
}

Output:

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

Explanation:

  1. The JsonObject and JsonParser classes from the com.google.gson package were added first. These program offers ways to read and write data in JSON.
  2. Then after, a main() function is included in the JsonExample class.
  3. A JSON string named jsonString is created in the main() method and includes a simple JSON object with the three fields name, age, and city.
  4. We build a jsonParser object of the JsonParser class. This class offers utilities to parse JSON data.
  5. We use the JsonParser class parse() function to convert the JSON string into a JsonElement object. The JsonElement is then converted into a JsonObject by using the getAsJsonObject() function of the JsonElement class.
  6. Finally, we print the JsonObject using the System.out.println() method. The output of the JsonObject is a string representation of the JSON object.

4. Using the org.json.simple library’s JSONParser class

This method involves calling the parse() method of the JSONValue class to parse the JSON string into a JSONObject or JSONArray object. The org.json.simple library provides a lightweight way to work with JSON data in Java.

Sample Code:

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonExample {
    public static void main(String[] args) {
        // JSON string
        String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";

        // Creating an instance of the JSONParser class
        JSONParser jsonParser = new JSONParser();

        try {
            // Parsing the JSON string to a JSONObject
            JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonString);

            // Printing the JSONObject
            System.out.println(jsonObject);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Output:

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

Code Explanation:

  1. We import the org.json.simple package’s JSONObject, JSONParser, and ParseException classes. These classes offer methods to read and write data in JSON.
  2. A main() method is provided whenever a JsonExample class is created.
  3. A JSON string called jsonString is made in the main() method and includes a simple JSON object with the three fields name, age, and city.
  4. We build a jsonParser instance of the JSONParser class. This class offers tools for parsing JSON data.
  5. To transform the JSON text into a JSONObject, we use the parse() function of the JSONParser class. We enclose this code in a try-catch block because the parse() method has had the ability to throw a ParseException.
  6. At last, we just use System.out.println() method to print the JSONObject. A string representation of the JSON object is the JSONObject’s output.

Best approach out of these four methods

The best approach for converting a JSON string to a JSON object in Java depends on the specific use case and requirements. However, based on the popularity and versatility of the libraries, a commonly used and recommended approach is to use the Gson library.

Here are some points that explain why:

  • Easy to use: Gson provides a simple and intuitive API for parsing and generating JSON data in Java. The library requires little preparation and is simple to set up and use.
  • Supports complex data types: Gson supports complex data types such as nested objects and arrays, and it can handle a wide range of JSON data structures.
  • High performance: While Gson may not be as fast as some other libraries, it still offers high performance and can handle large amounts of JSON data efficiently.
  • Widely used: Gson is a popular JSON parsing library in Java and is widely used in many Java projects. This indicates that there is a wealth of information, resources, and community support.
  • Customizable: Gson provides a range of customization options, such as registering custom serializers and deserializers, to fine-tune the parsing and generation of JSON data.

In summary, using Gson for converting a JSON string to a JSON object in Java is a good choice due to its simplicity, versatility, performance, and community support.

Sample problems

These are some problems on how to convert jsonstring to jsonobject in java.

Sample Problem 1

You have a JSON string with details on a collection of books. Using the Java JSONObject class from the JSON package, you must turn this JSON string into a JSONObject. The book titles must be extracted from the JSONObject and printed to the terminal once you have it.

Solution:

  1. Import the JSONObject class from the JSON library.
  2. By giving the JSON string to the function Object() { [native code] } of the JSONObject class, a JSONObject instance is created.
  3. To acquire the JSONArray containing the list of objects, use the getJSONArray() function on the JSONObject class.
  4. Loop through the JSONArray and extract the required values from each object using the getXXX() methods provided by the JSONObject class.
  5. Store the extracted values in variables for further use.
  6. Repeat step 4 and step 5 for all the objects in the JSONArray.
  7. Process the extracted data as required.
  8. Finally, close any open streams or connections to release resources.

Code:

import org.json.JSONObject; // import the JSONObject class from the JSON library

public class BookTitles {
    public static void main(String[] args) {
        // Define the JSON string
        String jsonString = "{\n" +
                "  \"books\": [\n" +
                "    {\n" +
                "      \"title\": \"The Great Gatsby\",\n" +
                "      \"author\": \"F. Scott Fitzgerald\",\n" +
                "      \"year\": 1925\n" +
                "    },\n" +
                "    {\n" +
                "      \"title\": \"To Kill a Mockingbird\",\n" +
                "      \"author\": \"Harper Lee\",\n" +
                "      \"year\": 1960\n" +
                "    },\n" +
                "    {\n" +
                "      \"title\": \"1984\",\n" +
                "      \"author\": \"George Orwell\",\n" +
                "      \"year\": 1949\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        // Create a new JSONObject instance from the JSON string
        JSONObject jsonObject = new JSONObject(jsonString);

        // Get the JSONArray that contains the list of books
        JSONArray books = jsonObject.getJSONArray("books");

        // Loop through the books and extract the titles
        for (int i = 0; i < books.length(); i++) {
            JSONObject book = books.getJSONObject(i);
            String title = book.getString("title");
            System.out.println(title);
        }
    }
}

Output:

The Great Gatsby
To Kill a Mockingbird
1984

Sample Problem 2

You are working on a Java programme that downloads data in JSON format from a distant API. Your task is to extract the name, age, and email address of all the users from the JSON string using the Jackson library’s ObjectMapper class and store them in a list of User objects. The User class has fields for name, age, and email. Finally, print the list of users to the console.

Solution:

  1. The JSON string containing user data is defined as a String variable jsonString.
  2. An ObjectMapper object is created to read and parse the JSON string into a tree-like structure of JsonNode objects.
  3. The readTree() method of the ObjectMapper object is used to parse the JSON string and return a root JsonNode object representing the top-level JSON value.
  4. The path() method of the JsonNode object is used to extract the users node, which is an array of JSON objects containing user data.
  5. A loop is used to iterate over each user JSON object in the users array. The name, age, and email fields are extracted for each user using the path() method, and a new User object is constructed with this data and added to the users list.
  6. Finally, the toString() method of each User object in the users list is called and printed to the console using a loop.

Code:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.ArrayList;
import java.util.List;

public class JsonToUserList {
    public static void main(String[] args) throws Exception {
        // JSON string with user data
        String jsonString = "{\"users\": [{\"name\": \"John Doe\", \"age\": 25, \"email\": \"[email protected]\"}, {\"name\": \"Jane Smith\", \"age\": 30, \"email\": \"[email protected]\"}]}";
        
        // Create ObjectMapper object
        ObjectMapper mapper = new ObjectMapper();
        
        // Read JSON string and convert to JsonNode object
        JsonNode rootNode = mapper.readTree(jsonString);
        
        // Extract user information and create User objects
        List<User> users = new ArrayList<>();
        JsonNode usersNode = rootNode.path("users");
        for (JsonNode userNode : usersNode) {
            String name = userNode.path("name").asText();
            int age = userNode.path("age").asInt();
            String email = userNode.path("email").asText();
            users.add(new User(name, age, email));
        }
        
        // Print list of users
        for (User user : users) {
            System.out.println(user);
        }
    }
}

class User {
    private String name;
    private int age;
    private String email;
    
    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    public String getEmail() {
        return email;
    }
    
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", email=" + email + "]";
    }
}

Output:

User [name=John Doe, age=25, [email protected]]
User [name=Jane Smith, age=30, [email protected]]

Sample Problem 3

You are developing a Java software that uses a remote API to fetch a JSON string. Your task is to use the Gson library’s JsonParser class to convert the JSON string into a JsonObject. The “name” and “age” keys’ values must be taken out of the JsonObject and put in a Map object. Finally, print the Map object to the console.

Solution:

  1. We begin by importing the Gson library’s essential classes before beginning to parse the JSON string.
  2. We declare the JSON string that we want to parse.
  3. The JSON string will be parsed using a JsonParser object that we construct next.
  4. To parse the JSON string and produce a JsonObject from it, we use the parse() function of the JsonParser object.
  5. We create a HashMap object to store the key-value pairs extracted from the JsonObject.
  6. We employ the JsonObject’s get() function to get the values associated with the “name” and “age” keys.
  7. We add the extracted values to the HashMap with the corresponding keys.
  8. Lastly, we use System.out to print the HashMap object to the console. println().

Code:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) {
        // Sample JSON string
        String jsonString = "{\"name\": \"John Doe\", \"age\": 30, \"email\": \"[email protected]\"}";

        // Use Gson's JsonParser to parse the JSON string into a JsonObject
        JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();

        // Extract the values of the "name" and "age" keys from the JsonObject and put them in a Map
        Map<String, Object> map = new HashMap<>();
        map.put("name", jsonObject.get("name").getAsString());
        map.put("age", jsonObject.get("age").getAsInt());

        // Print the Map object to the console
        System.out.println(map);
    }
}

Output:

{name=John Doe, age=30}

Sample Problem 4

You are working on a Java application that gets data as a JSON string from a distant API. Your objective is to parse the JSON string and produce a JSONObject from it using the JSONParser class from the org.json.simple library. After that, you must extract the JSONObject’s “name” and “age” key values and print them to the console.

Solution:

  1. Import the required packages from org.json.simple.
  2. Create a JSONParser object to parse the JSON string.
  3. Just use parse() function of the JSONParser object to convert the JSON string into a JSONObject.
  4. You can obtain the values related to the “name” and “age” keys through the JSONObject object’s get() method.
  5. Print the values to the console.

Code:

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonParserExample {

    public static void main(String[] args) {
        // Declare the JSON string to parse
        String jsonString = "{\"name\":\"John\", \"age\":30}";

        // Create a JSONParser object
        JSONParser parser = new JSONParser();

        try {
            // Parse the JSON string and create a JSONObject from it
            JSONObject json = (JSONObject) parser.parse(jsonString);

            // Extract the values associated with "name" and "age" keys
            String name = (String) json.get("name");
            long age = (Long) json.get("age");

            // Print the extracted values to the console
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Output:

Name: John
Age: 30

Conclusion

In conclusion, there are various techniques, each with pros and cons on how to change json string to json object in java. The project’s needs and the developer’s experience determine the method to use.

The JSON libraries available for Java, such as Jackson, Gson, and JSON.simple, provide a wide range of tools for parsing and manipulating JSON data.

Understanding the various methods of converting JSON strings to JSONObjects and their implementation in Java can be helpful in developing robust and efficient applications that handle JSON data.