Gson – Convert A String To JsonObject

This quick tutorial is going to illustrate how to convert a Json string to JsonObject using Gson, a Java serialization/deserialization library to convert Java Objects into JSON and back.

1. Prerequisites

We will need to include Gson library dependency in our classpath. To use Gson with Maven:

To use Gson with Gradle:

2. Convert A String To JsonObject Using Gson

2.1. Using Gson Class

We can use the Gson class to convert a string to JsonObject using Gson library, for example:

This fromJson method deserializes the specified Json string into an object of the JsonObject type, and then we can access all necessary properties.

2.2. Using JsonParser Class

Another way to convert a string to JsonObject is to use the JsonParser class which is also included in the Gson library, for example:

We use the parse method of the JsonParser class in order to parss the specified JSON string into a JsonObject from which we can access all necessary properties.

3. Conclusions

The tutorial has illustrated us several ways to convert a string to JsonObject using Gson library. For those who are familiar with Gson class, we can leverage it to convert a string to any kind of POJO we have defined structure while the JsonParser provides us a simple way to convert a string directly to JsonObject.

The sample source code presented in the tutorial is available on my GitHub project. And it’s a Maven based project; it should be easy to be imported into IDE such as Eclipse, IntelliJ, etc.

Below are other Gson related tutorials for your references:

Ignore or Exclude Field in Gson

Gson Example with Maven and Gradle