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 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: '', 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.


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

What is the JsonElement class?

The 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": "",
  "website": "",
  "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.


public class JsonElementExample {
    public static void main(String... args) {
        String jsonString = "{\n" +
                "  \"firstName\": \"Simple\",\n" +
                "  \"lastName\": \"Solution\",\n" +
                "  \"email\": \"\",\n" +
                "  \"website\": \"\",\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: ");
The output is:
Converted JsonElement object: 
{"firstName":"Simple","lastName":"Solution","email":"","website":"","address":{"street":"Simple Street","city":"City Name","country":"Country Name"}}

Happy Coding 😊