Java Gson Convert JSON String to JsonElement

Tags: JSON gson Gson fromJson JsonElement JSON String to JsonElement

In This Java Gson tutorial we learn how to convert a JSON String into a com.google.gson.JsonElement object of the Gson library.

How to add Gson to the Java project

To use the Gson library in the Gradle build project, add the following dependency into the build.gradle file.

implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7'

To use the Gson library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.7</version>
</dependency>

Or you can download the Gson jar file from Maven Central at gson-2.8.7.jar

To have more information about the Gson library you can visit the project repository at github.com/google/gson

What is the JsonElement class?

The com.google.gson.JsonElement is a class in the Gson library which represents an element of JSON. From a given JsonElement object we can use the toString() method to return a JSON String.

How to convert JSON String to JsonElement in Java

For example, we have a JSON String as below.

{
  "firstName": "Simple",
  "lastName": "Solution",
  "email": "contact@simplesolution.dev",
  "website": "https://simplesolution.dev",
  "address": {
    "street": "Simple Street",
    "city": "City Name",
    "country": "Country Name"
  }
}

In the following Java example we learn how to use the Gson.fromJson() method to convert the JSON String above to a JsonElement object.

JsonElementExample.java

import com.google.gson.Gson;
import com.google.gson.JsonElement;

public class JsonElementExample {
    public static void main(String... args) {
        String jsonString = "{\n" +
                "  \"firstName\": \"Simple\",\n" +
                "  \"lastName\": \"Solution\",\n" +
                "  \"email\": \"contact@simplesolution.dev\",\n" +
                "  \"website\": \"https://simplesolution.dev\",\n" +
                "  \"address\": {\n" +
                "    \"street\": \"Simple Street\",\n" +
                "    \"city\": \"City Name\",\n" +
                "    \"country\": \"Country Name\"\n" +
                "  }\n" +
                "}";

        Gson gson = new Gson();
        JsonElement jsonElement = gson.fromJson(jsonString, JsonElement.class);

        System.out.println("Converted JsonElement object: ");
        System.out.println(jsonElement.toString());
    }
}
The output is:
Converted JsonElement object: 
{"firstName":"Simple","lastName":"Solution","email":"contact@simplesolution.dev","website":"https://simplesolution.dev","address":{"street":"Simple Street","city":"City Name","country":"Country Name"}}

Happy Coding 😊