×

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

Factorial of a Large Number in Java

We've already talked about a number's factorial. We must still go over the factorial of a large number separately, though. The method used to determine the factorial of a small...

8 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.