Guide to Jackson Library in Java

Introduction

Jackson is a popular library for processing JSON in Java. It provides a suite of tools for serializing Java objects to JSON and deserializing JSON to Java objects. Jackson is highly customizable and can handle various data formats such as XML, YAML, CSV, and more.

Check out the advanced Jackson Library in Java: Java Jackson JSON Tutorial with Examples.

Installation

To use Jackson, add the following dependencies to your pom.xml if you're using Maven:

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.14.1</version> <!-- or the latest version -->
    </dependency>
</dependencies>

For Gradle:

dependencies {
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.14.1' // or the latest version
}

Basic Usage

ObjectMapper

The ObjectMapper class is the core of Jackson, providing functionality for reading and writing JSON.

Example: Serialize Java Object to JSON

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class SerializeExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        User user = new User("Ramesh", 30);
        String jsonString = objectMapper.writeValueAsString(user);
        System.out.println("JSON String: " + jsonString);
    }

    static class User {
        private String name;
        private int age;

        public User() {
        }

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

        // getters and setters
        public String getName() {
            return name;
        }

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

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

Output

JSON String: {"name":"Ramesh","age":30}

Example: Deserialize JSON to Java Object

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class DeserializeExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = "{\"name\":\"Ramesh\",\"age\":30}";
        User user = objectMapper.readValue(jsonString, User.class);
        System.out.println("User: " + user.getName() + ", Age: " + user.getAge());
    }

    static class User {
        private String name;
        private int age;

        public User() {
        }

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

        // getters and setters
        public String getName() {
            return name;
        }

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

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

Output

User: Ramesh, Age: 30

Advanced Usage

Annotations

Jackson provides various annotations to control the serialization and deserialization processes.

Example: @JsonProperty

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonPropertyExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = "{\"full_name\":\"Ramesh\",\"age\":30}";
        User user = objectMapper.readValue(jsonString, User.class);
        System.out.println("User: " + user.getFullName() + ", Age: " + user.getAge());
    }

    static class User {
        @JsonProperty("full_name")
        private String fullName;
        private int age;

        public User() {
        }

        public User(String fullName, int age) {
            this.fullName = fullName;
            this.age = age;
        }

        // getters and setters
        public String getFullName() {
            return fullName;
        }

        public void setFullName(String fullName) {
            this.fullName = fullName;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

Output

User: Ramesh, Age: 30

Example: @JsonIgnore

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonIgnoreExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        User user = new User("Ramesh", 30, "password123");
        String jsonString = objectMapper.writeValueAsString(user);
        System.out.println("JSON String: " + jsonString);
    }

    static class User {
        private String name;
        private int age;
        @JsonIgnore
        private String password;

        public User() {
        }

        public User(String name, int age, String password) {
            this.name = name;
            this.age = age;
            this.password = password;
        }

        // getters and setters
        public String getName() {
            return name;
        }

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

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
}

Output

JSON String: {"name":"Ramesh","age":30}

Custom Serializer and Deserializer

Jackson allows you to create custom serializers and deserializers for complex data types.

Example: Custom Serializer

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.IOException;

public class CustomSerializerExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        User user = new User("Ramesh", 30);
String jsonString = objectMapper.writeValueAsString(user); System.out.println("JSON String: " + jsonString); } static class User { private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } // getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } static class UserSerializer extends JsonSerializer<User> { @Override public void serialize(User user, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeStringField("user_name", user.getName()); gen.writeNumberField("user_age", user.getAge()); gen.writeEndObject(); } } }

Example: Custom Deserializer

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.io.IOException;

public class CustomDeserializerExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = "{\"user_name\":\"Ramesh\",\"user_age\":30}";
User user = objectMapper.readValue(jsonString, User.class); System.out.println("User: " + user.getName() + ", Age: " + user.getAge()); } static class User { private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } // getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } static class UserDeserializer extends JsonDeserializer<User> { @Override public User deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = p.getCodec().readTree(p); String name = node.get("user_name").asText(); int age = node.get("user_age").asInt(); return new User(name, age); } } }

Working with Collections

Example: Serialize and Deserialize a List

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

public class ListExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        List<User> users = List.of(new User("Ramesh", 30), new User("Pramod", 25));
String jsonString = objectMapper.writeValueAsString(users); System.out.println("JSON String: " + jsonString); List<User> deserializedUsers = objectMapper.readValue(jsonString, new TypeReference<List<User>>() {}); deserializedUsers.forEach(user -> System.out.println("User: " + user.getName() + ", Age: " + user.getAge())); } static class User { private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } // getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } }

Output

JSON String: [{"name":"Ramesh","age":30},{"name":"Pramod","age":25}]
User: Ramesh, Age: 30
User: Pramod
, Age: 25

Example: Serialize and Deserialize a Map

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class MapExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Integer> map = Map.of("Ramesh", 30, "Pramod", 25);
String jsonString = objectMapper.writeValueAsString(map); System.out.println("JSON String: " + jsonString); Map<String, Integer> deserializedMap = objectMapper.readValue(jsonString, new TypeReference<Map<String, Integer>>() {}); deserializedMap.forEach((name, age) -> System.out.println("Name: " + name + ", Age: " + age)); } }

Output

JSON String: {"Ramesh":30,"Pramod":25}
Name: Ramesh, Age: 30
Name: Pramod
, Age: 25

Handling Dates

Example: Serialize and Deserialize Java Date

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));

        DateHolder dateHolder = new DateHolder(new Date());
        String jsonString = objectMapper.writeValueAsString(dateHolder);
        System.out.println("JSON String: " + jsonString);

        DateHolder deserializedDateHolder = objectMapper.readValue(jsonString, DateHolder.class);
        System.out.println("Date: " + deserializedDateHolder.getDate());
    }

    static class DateHolder {
        private Date date;

        public DateHolder() {
        }

        public DateHolder(Date date) {
            this.date = date;
        }

        // getters and setters
        public Date getDate() {
            return date;
        }

        public void setDate(Date date) {
            this.date = date;
        }
    }
}

Output

JSON String: {"date":"2024-05-17"}
Date: Fri May 17 00:00:00 GMT 2024

Customizing ObjectMapper

Example: Enabling Pretty Print

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class PrettyPrintExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        User user = new User("Ramesh", 30);
String jsonString = objectMapper.writeValueAsString(user); System.out.println("JSON String: " + jsonString); } static class User { private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } // getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } }

Output

JSON String: {
  "name" : "Ramesh",
"age" : 30 }

Conclusion

Jackson is a powerful and flexible library for processing JSON in Java. This tutorial covered the basics of Jackson, including setting up the ObjectMapper, serializing and deserializing Java objects, working with collections, handling dates, and customizing the ObjectMapper. Additionally, it demonstrated advanced features such as custom serializers and deserializers, and various Jackson annotations. 

Check out the advanced Jackson Library in Java: Java Jackson JSON Tutorial with Examples.

Also, check out the official Jackson documentation

Comments