×

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the JSON String alone is not a wise choice because handling it might be challenging. We must transform JSON String to JSON Object in order to obtain values because of the evolution and demand of the technology. There are some open-source utilities that enable us to convert JSON String to JSON Object in order to fix this issue. This section includes a detailed explanation and example of how to convert a JSON String to a JSON Object. Let's have a look at JSON format before going on to the main subject.

jsonStringExpl =   
{  
"name" : "JavaTpoint",  
"nickname" : "JTP",  
"id" : 122,  
"age" : 20,    
"height" : 169,    
"lastOverScore" : [5, 2, 4, 4, 3, 6]  
}  

The first two attributes in the aforementioned JSON format are Strings, the following three are numeric, and the final attribute is a JSON array.

JSON String to JSON Object Conversion

The three libraries listed below are used to translate strings into JSON objects in Java:

Use of the Gson Library

JSON-Simple Library is used.

Jackson Public Library.

Gson Library usage

Google offers a robust and open-source Java library called Gson. It is used to translate JSON Object to JSON String and JSON String to JSON String. To change a JSON String into a JSON Object, use the following line of code.

1.  Gson g = new Gson();

2. Student s = g.fromJson(jsonString, Student.class)

The toJson() method also allows us to convert JSON Object to JSON String.

  • String str = g.toJson(p);

Example of conversion of string to Json object using Gson Library.

JSON-Simple Library is utilized

Another free Java package that can convert JSON String to JSON Object is this one. The JSON-Simple library has the benefit of being compact. It is ideal in situations where a memory-constrained environment is crucial. Keep in mind that JDK 1.2 is also compatible. It implies that we can utilize it with a legacy project that isn't Java 5 compatible. The JSON String is transformed into a JSON Object using the following statements.

1. SONParser parser = new JSONParser();

2. JSONObject JSON = (JSONObject) parser.parse(stringToParse);

Jackson Library

Jackson Library is a well-liked and effective Java library for mapping Java objects to JSON and the other way around. It has a wide range of functions, performs quickly, and even enables streaming. Large JSON outputs from online services can be parsed by the stream without needing to load them entirely into memory. The JSON String representing a student is transformed into a Java class by the following statement.

1. Student student = new ObjectMapper().readValue(jsonString, Student.class);

Jackson library's drawback is that it needs JDK 1.5 or later. As a result, it won't fit there if we are working with an older version. The Jackson library's lack of support for J2ME is another drawback.

Exampl1.java

import org.json.*;  
public class Example1 
{  
public static void main(String[] args)   
{  
String s = "{\"name\": \"JavaTpoint\", \"language\": \"Java\"}";  
JSONObject json = new JSONObject(s);  
System.out.println(json.toString());  
String technology = json.getString("language");  
System.out.println(language);  
}  
}  

Output:

JavaTpoint
Java

Related Topics

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.