Jackson – Convert JSON to Java Object Example

1. Introduction

Jackson is a widely-used Java library that allows for easy serialization and deserialization of Java objects to and from JSON format. In this guide, we'll focus on how you can deserialize, or convert, a JSON string into its corresponding Java object using Jackson.

2. Example Steps

1. Add the necessary Jackson library dependencies to your project.

2. Create a Java class that maps to the structure of the JSON you're deserializing.

3. Use Jackson's ObjectMapper class to deserialize the JSON string into the Java object.

4. Display the resultant Java object's attributes to the console.

3. Convert JSON to Java Object Example

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonJsonToObjectExample {

    public static void main(String[] args) {
        // Sample JSON string.
        String jsonString = "{\"firstName\":\"Alice\",\"lastName\":\"Smith\",\"age\":25}";

        try {
            // Initialize ObjectMapper instance.
            ObjectMapper objectMapper = new ObjectMapper();

            // Convert JSON string to Java object.
            Person person = objectMapper.readValue(jsonString, Person.class);

            // Print out the Java object attributes.
            System.out.println("First Name: " + person.getFirstName());
            System.out.println("Last Name: " + person.getLastName());
            System.out.println("Age: " + person.getAge());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    static class Person {
        private String firstName;
        private String lastName;
        private int age;

        // Standard getters, setters, and other methods...
    }
}

Output:

First Name: Alice
Last Name: Smith
Age: 25

4. Step By Step Explanation

1. The program starts by defining a simple Java Person class that will act as the model for the JSON string we are deserializing. This class has attributes like firstName, lastName, and age which correspond to keys in the JSON string.

2. We then initialize Jackson's ObjectMapper, the class responsible for the conversion process between Java objects and JSON.

3. The readValue method on the ObjectMapper instance is used to deserialize our JSON string into a Person object.

4. Lastly, we output the attributes of the Person object to the console. This shows that the JSON string has been successfully converted into its corresponding Java object using Jackson.


Comments