Java Gson fromJson() Example

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.
The Gson.fromJson() method deserializes the specified JSON into an object of the specified class.
Check out top GSON tutorial at Google GSON Tutorial.

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 example uses fromJson() method to read JSON into a Java object.
import com.google.gson.Gson;

class User {

    private final String firstName;
    private final String lastName;

    public User(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\":\"Tom\", \"lastName\": \"Broody\"}";

        Gson gson = new Gson();
        User user = gson.fromJson(json_string, User.class);

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


Comments