Create java object from json (GSON)

In the previous blog we showed how to convert java object to json. In this post we will show how to create java object from json using GSON library.

Firs of all we need to add following dependency into the maven pom.xml

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

For this we need to do following:

Gson gson = new GsonBuilder().create();
Object object = gson.fromJson(jsonString, Object.class);

The full example is following:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonToModelExample {

    private static class User {

        private String name;

        private String emailAddress;

        public User(String name, String emailAddress) {
            this.name = name;
            this.emailAddress = emailAddress;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getEmailAddress() {
            return emailAddress;
        }

        public void setEmailAddress(String emailAddress) {
            this.emailAddress = emailAddress;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", emailAddress='" + emailAddress + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        
        final String json = "{\"name\":\"testName\",\"emailAddress\":\"testEmailAddress\"}";
        Gson gson = new GsonBuilder().create();
        User user = gson.fromJson(json, User.class);
        System.out.println(user);

    }
}

And the output should be:

User{name='testName', emailAddress='testEmailAddress'}