Table of contents
1.
Introduction 
2.
Using Gson Library
2.1.
Java
3.
Using JSON-Simple Library
3.1.
Java
4.
Jackson Library
4.1.
Java
5.
Frequently Asked Questions
5.1.
Can I use any of these libraries to convert a JSON object back to a JSON string?
5.2.
Which library is the most efficient for converting large JSON strings?
5.3.
Do I need to add any external dependencies to use these libraries in my Java project?
6.
Conclusion
Last Updated: Aug 10, 2024
Medium

Convert Json String to Json Object

Author Ravi Khorwal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and for machines to parse and generate. It is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C-family of languages. JSON is built on two structures: a collection of name/value pairs and an ordered list of values. 

Convert Json String to Json Object

In this article, we will learn how to convert a JSON string to a JSON object using different libraries in Java. We will talk about the Gson library, JSON-Simple library, and Jackson library.

Using Gson Library

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code for.

For example : 

  • Java

Java

import com.google.gson.Gson;

import com.google.gson.JsonObject;

public class JsonStringToJsonObjectExample {

   public static void main(String[] args) {

       // JSON string

       String jsonString = "{\"name\":\"Rahul\",\"age\":25,\"city\":\"New York\"}";

       // Create Gson object

       Gson gson = new Gson();

       // Convert JSON string to JSON object

       JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);

       // Access values from JSON object

       String name = jsonObject.get("name").getAsString();

       int age = jsonObject.get("age").getAsInt();

       String city = jsonObject.get("city").getAsString();       

       // Print values

       System.out.println("Name: " + name);

       System.out.println("Age: " + age);

       System.out.println("City: " + city);

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

Name: Rahul
Age: 25
City: New York


In this example, we first create a JSON string that we want to convert to a JSON object. We then create a Gson object and use its `fromJson()` method to convert the JSON string to a `JsonObject`. We can then access the values from the JSON object using the `get()` method and the appropriate getter method (`getAsString()`, `getAsInt()`, etc.).

Using JSON-Simple Library

JSON-Simple is another Java library that can be used to parse JSON data and convert it to Java objects. It is a simple and lightweight library that is easy to use.

For example : 

  • Java

Java

import org.json.simple.JSONObject;

import org.json.simple.parser.JSONParser;

import org.json.simple.parser.ParseException;

public class JsonStringToJsonObjectExample {

   public static void main(String[] args) {

       // JSON string

       String jsonString = "{\"name\":\"Rinki\",\"age\":30,\"city\":\"London\"}";       

       // Create JSON parser

       JSONParser parser = new JSONParser();      

       try {

           // Parse JSON string to JSON object

           JSONObject jsonObject = (JSONObject) parser.parse(jsonString);       

           // Access values from JSON object

           String name = (String) jsonObject.get("name");

           long age = (long) jsonObject.get("age");

           String city = (String) jsonObject.get("city");           

           // Print values

           System.out.println("Name: " + name);

           System.out.println("Age: " + age);

           System.out.println("City: " + city);

       } catch (ParseException e) {

           e.printStackTrace();

       }

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

Name: Rinki
Age: 30
City: London


In this example, we first create a JSON string that we want to convert to a JSON object. We then create a `JSONParser` object and use its `parse()` method to parse the JSON string and convert it to a `JSONObject`. We can then access the values from the JSON object using the `get()` method and cast them to their appropriate data types.

You need to remember that the `parse()` method throws a `ParseException` if the JSON string is not valid, so we need to handle this exception using a try-catch block.

Jackson Library

Jackson is a popular Java library for processing JSON data. It provides a simple way to convert JSON strings to Java objects and vice versa. Jackson is known for its high performance and flexibility.

For example : 

  • Java

Java

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonStringToJsonObjectExample {

   public static void main(String[] args) {

       // JSON string

       String jsonString = "{\"name\":\"Harsh\",\"age\":35,\"city\":\"Mumbai\"}";      

       // Create ObjectMapper object

       ObjectMapper mapper = new ObjectMapper();      

       try {

           // Convert JSON string to JSON object

           JsonNode jsonNode = mapper.readTree(jsonString);        

           // Access values from JSON object

           String name = jsonNode.get("name").asText();

           int age = jsonNode.get("age").asInt();

           String city = jsonNode.get("city").asText();          

           // Print values

           System.out.println("Name: " + name);

           System.out.println("Age: " + age);

           System.out.println("City: " + city);

       } catch (JsonProcessingException e) {

           e.printStackTrace();

       }

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

Name: Harsh
Age: 35
City: Mumbai


In this example, we first create a JSON string that we want to convert to a JSON object. We then create an `ObjectMapper` object from the Jackson library. We use the `readTree()` method of the `ObjectMapper` to parse the JSON string and convert it to a `JsonNode` object.

We can then access the values from the `JsonNode` object using the `get()` method and the appropriate accessor methods (`asText()`, `asInt()`, etc.).

Just remember that the `readTree()` method throws a `JsonProcessingException` if there is an error while parsing the JSON string, so we need to handle this exception using a try-catch block.

Note: Jackson provides a lot of flexibility and customization options for handling JSON data. It supports annotations for mapping JSON fields to Java object properties, handling collections, and much more.

Frequently Asked Questions

Can I use any of these libraries to convert a JSON object back to a JSON string?

Yes, all three libraries (Gson, JSON-Simple, and Jackson) provide methods to convert a JSON object back to a JSON string.

Which library is the most efficient for converting large JSON strings?

Jackson is known for its high performance and is often the preferred choice for handling large JSON strings efficiently.

Do I need to add any external dependencies to use these libraries in my Java project?

Yes, you need to add the corresponding library dependency (Gson, JSON-Simple, or Jackson) to your project's classpath or build configuration.

Conclusion

In this article, we learned how to convert a JSON string to a JSON object using three popular Java libraries: Gson, JSON-Simple, and Jackson. We saw proper code examples for each library, which showed how to parse a JSON string, convert it to a JSON object, and access the values from the JSON object. These libraries provide convenient methods and offer different features and performance characteristics. 

You can also check out our other blogs on Code360

Live masterclass