Java Gson fromJson Example

In the example, we use Gson fromJson() method to read JSON into a Java object.
Gson is a Java serialization/deserialization library to convert Java Objects into JSON and back. Gson was created by Google for internal use and later open-sourced.

Java Gson Maven dependency

This is a Maven dependency for Gson.
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

Java Gson fromJson Example

The fromJson() method deserializes the specified JSON into an object of the specified class.
package net.javaguides.gson;

import com.google.gson.Gson;

class UserData {

    private final String firstName;
    private final String lastName;

    public UserData(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }


    @Override
    public String toString() {
        return new StringBuilder().append("User{").append("First name: ")
            .append(firstName).append(", Last name: ")
            .append(lastName).append("}").toString();
    }
}

public class GsonFromJson {

    public static void main(String[] args) {

        String json_string = "{\"firstName\":\"Amir\", \"lastName\": \"Khan\"}";

        Gson gson = new Gson();

        UserData user = gson.fromJson(json_string, UserData.class);

        System.out.println(user);
    }
}
Output:
User{First name: Amir, Last name: Khan}

Reference

Comments