Javatpoint Logo
Javatpoint Logo

How to Convert String to JSON Object in Java?

Nowadays, it is very common to receive data in JSON String format instead of XML. When we deal with JSON String in Java, it does not convert the JSON String to JSON Object. But use the JSON String always is not a good option because it is difficult to deal with it. Due to the change and demand of the technology, we need to convert JSON String to JSON Object to retrieve values. to resolve this problem there are some open-source libraries that allow us to convert JSON String to JSON Object. In this section, we have explained how to convert JSON String to JSON Object in detail with example. Before moving to the main topic, let's have a look at JSON format.

The above JSON format contains six attributes out of which the first two are Strings, the next three are numeric and at last a JSON array.

Convert JSON String to JSON Object

There are the following three libraries are used to convert String to JSON Object in Java:

  • Using Gson Library
  • Using JSON-Simple Library
  • Jackson Library

Using Gson Library

Gson is an open-source and rich Java library provided by Google. It is used to convert JSON String to equivalent JSON Object and JSON Object to JSON String. The following line of code is used to convert JSON String to JSON Object.

We can also convert JSON Object to JSON String by using the toJson() method.

Using JSON-Simple Library

It is another open-source Java library used for converting JSON String to JSON Object. The advantage of the JSON-Simple library is its small size. It is perfect where the memory constraint environment is important. Note that it is also compatible with JDK 1.2. It means that we can use it with a legacy project which is not in Java 5. We use the following statements to convert the JSON String to JSON Object.

Using Jackson Library

Jackson library is an efficient and widely used Java library to map Java objects to JSON and vice-versa. It is rich in features, fast in performance, and also supports streaming. The stream can parse a large JSON output from web services without loading it fully in memory. The following statement converts JSON String representing a student into a Java class representing the student.

The disadvantage of Jackson library is that it requires at least JDK 1.5. Therefore, if we are dealing with an older version, it will not fit there. Another disadvantage of the Jackson library is that it does not support J2ME.

JSON String to JSON Object Conversion Example

In the following program, we have converted a JSON String to JSON Object.

JsonStringToJsonObjectExample.java

Output:

17
Andrew
18
Peter
19
Tom

Let's see another example.

JsonStringToJsonObjectExample2.java

Output:

Sam Smith
Python





Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA