Create java object from json (Jackson)

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 Jackson library.

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

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>

For this we need to do following:

ObjectMapper objectMapper = new ObjectMapper();
Object object = objectMapper.readValue(json, Object.class);

The full example is following:

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JacksonJsonToModelExample {

    private static class User {

        private String name;

        private String 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{" +
                    "emailAddress='" + emailAddress + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {

        final String json = "{\"name\":\"testName\",\"emailAddress\":\"testEmailAddress\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(json, User.class);
        System.out.println(user);

    }
}

And the output should be:

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