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.

Java Gson fromJson Example

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


class UserData {

    private final String firstName;
    private final String lastName;

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

    public String toString() {
        return new StringBuilder().append("User{").append("First name: ")
            .append(firstName).append(", Last name: ")

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);

User{First name: Amir, Last name: Khan}