CodeGym /Courses /JAVA 25 SELF /Jackson — reading and writing JSON, annotations

Jackson — reading and writing JSON, annotations

JAVA 25 SELF
Level 46, Lesson 1
Available

1. Introduction to Jackson

Data exchange between a Java application and the outside world can often be framed as the question: “How do we turn a Java object into JSON — and back?” You could, of course, write your own parser using String.split and regexes (and even enjoy the pain), but nobody does that in real projects.

There are several popular libraries for working with JSON in Java. The main one is Jackson. It’s so popular that it’s included in Spring Boot and used by many other frameworks and libraries.

What is Jackson?

Jackson is a powerful and flexible library for serialization (converting a Java object to JSON) and deserialization (the reverse operation). It consists of several modules, but for 90% of tasks you’ll need two:

  • jackson-core — the core, a low-level parser.
  • jackson-databind — a high-level module that can turn Java objects into JSON and back.

All you need to know to start: if you see the ObjectMapper class — that’s Jackson.

Jackson is considered the de facto standard for working with JSON in Java because it combines simplicity and power. To serialize or deserialize data, you literally need just a couple of lines of code, which makes the library convenient even for beginners. At the same time, it’s not limited to basic features: thanks to annotations and a wealth of settings, you can finely control how data is turned into objects and back, whether it’s collections, nested entities, or dates in different formats.

It’s also important that Jackson is very fast and efficient, which is critical for real-world projects with large volumes of data. The library’s maintainers support new versions of Java and relevant changes to the JSON standard — Jackson remains a reliable choice for both simple applications and large enterprise systems.

2. Reading JSON (deserialization)

Let’s try to read a JSON string and turn it into a Java object. To do this, we’ll need:

  • A data class (for example, Person)
  • The ObjectMapper class from Jackson

Adding Jackson

If you use Maven, add to pom.xml:

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

If you’re using Gradle — similarly:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.0'

Example class

public class Person {
    public String name;
    public int age;
}

Note: For simplicity, the fields are public. We’ll discuss working with private fields and getters/setters later.

JSON example

{
  "name": "Alice",
  "age": 30
}

Deserialization: turning JSON into an object

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        String json = "{\"name\": \"Alice\", \"age\": 30}";

        ObjectMapper mapper = new ObjectMapper();
        Person person = mapper.readValue(json, Person.class);

        System.out.println(person.name); // Alice
        System.out.println(person.age);  // 30
    }
}

Here Jackson parses the JSON string, finds fields whose names match the class’s fields or getters, and populates the object with the corresponding values using readValue.

Deserializing a list of objects

Suppose we have an array:

[
  { "name": "Bob", "age": 22 },
  { "name": "Eve", "age": 27 }
]

Deserialize into a list:

import com.fasterxml.jackson.core.type.TypeReference;
// ...

String json = "[{\"name\": \"Bob\", \"age\": 22}, {\"name\": \"Eve\", \"age\": 27}]";
ObjectMapper mapper = new ObjectMapper();

List<Person> people = mapper.readValue(json, new TypeReference<List<Person>>() {});

for (Person p : people) {
    System.out.println(p.name + " (" + p.age + ")");
}

You might be wondering: why not simply write mapper.readValue(json, List.class)? Remember that generics in Java are erased at compile time. That’s why we need a TypeReference so Jackson knows that the list contains objects of type Person.

3. Writing JSON (serialization)

Now let’s perform the reverse operation: turn a Java object into a JSON string.

Example

ObjectMapper mapper = new ObjectMapper();

Person person = new Person();
person.name = "Charlie";
person.age = 40;

String json = mapper.writeValueAsString(person);
System.out.println(json);
// {"name":"Charlie","age":40}

Serializing a list of objects

ObjectMapper mapper = new ObjectMapper();

List<Person> people = new ArrayList<>();
people.add(new Person("Anna", 25));
people.add(new Person("Dmitry", 31));

String json = mapper.writeValueAsString(people);
System.out.println(json);
// [{"name":"Anna","age":25},{"name":"Dmitry","age":31}]

Writing to a file

ObjectMapper mapper = new ObjectMapper();

Person person = new Person();
person.name = "Charlie";
person.age = 40;

mapper.writeValue(new File("person.json"), person);
// The file person.json now contains a JSON object

Pretty JSON

By default, Jackson writes everything on one line. But there’s also a more human-friendly option — pretty printing. This means the JSON string is output in a readable form: with indentation, line breaks, and neat formatting.

Unlike “regular” JSON, which is usually written on one line for compactness, the “pretty” variant is for people — to make it easy to inspect the data structure in logs, files, or on screen.

ObjectMapper mapper = new ObjectMapper();

Person person = new Person();
person.name = "Charlie";
person.age = 40;

String prettyJson = mapper.writerWithDefaultPrettyPrinter()
                          .writeValueAsString(person);

System.out.println(prettyJson);
/*
{
  "name" : "Charlie",
  "age" : 40
}
*/

4. Jackson annotations

Jackson supports many annotations that let you control the serialization and deserialization process. Here are the most useful ones:

@JsonProperty

Allows you to specify the field name in JSON if it differs from the field name in the class.

import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {
    @JsonProperty("full_name")
    public String name;

    public int age;
}
{"full_name": "Olga", "age": 28}

Jackson will understand that the full_name field from JSON should be written to the object’s name field.

@JsonIgnore

If you don’t want to serialize or deserialize a particular field:

import com.fasterxml.jackson.annotation.JsonIgnore;

public class Person {
    public String name;

    @JsonIgnore
    public int age;
}

The age field won’t appear in JSON, even if it exists on the object.

@JsonInclude

Controls which fields end up in JSON. For example, serialize only non-null fields:

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
    public String name;
    public Integer age;
}

If age == null, there will be no "age" key in JSON.

@JsonFormat

Allows you to specify the format for serializing dates and times.

import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;

public class Event {
    public String title;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    public Date date;
}
Event event = new Event();
event.title = "Hackathon";
event.date = new Date();

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(event);
// {"title":"Hackathon","date":"2024-06-07 15:23:00"}

Example: everything together

import com.fasterxml.jackson.annotation.*;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
    @JsonProperty("full_name")
    private String name;

    private int age;

    @JsonIgnore
    private String password;

    // Getters and setters are required for private fields!
    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; }
}

5. Practice: serialization and deserialization with annotations

Let’s expand your training app — now we have a User class with private fields, a registration date, and a password that must not go into JSON.

import com.fasterxml.jackson.annotation.*;
import java.util.Date;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
    @JsonProperty("login")
    private String username;

    private int age;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private Date registered;

    @JsonIgnore
    private String password;

    // Getters and setters are required!
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }

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

    public Date getRegistered() { return registered; }
    public void setRegistered(Date registered) { this.registered = registered; }

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

Serialization

import com.fasterxml.jackson.databind.ObjectMapper;
import java.text.SimpleDateFormat;

ObjectMapper mapper = new ObjectMapper();

User user = new User();
user.setUsername("superuser");
user.setAge(42);
user.setRegistered(new SimpleDateFormat("yyyy-MM-dd").parse("2024-06-07"));
user.setPassword("qwerty123"); // Will not be in JSON!

String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);

System.out.println(json);
/*
{
  "login" : "superuser",
  "age" : 42,
  "registered" : "2024-06-07"
}
*/

Deserialization

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();

String json = "{ \"login\": \"superuser\", \"age\": 42, \"registered\": \"2024-06-07\" }";
User user = mapper.readValue(json, User.class);

System.out.println(user.getUsername()); // superuser
System.out.println(user.getAge());      // 42
System.out.println(user.getRegistered());// Fri Jun 07 00:00:00 ...
System.out.println(user.getPassword()); // null (and that's good!)

6. Common mistakes when working with Jackson

Error #1: Missing no-args constructor.
Jackson won’t be able to instantiate a class if it doesn’t have a no-args constructor. This often happens in classes where only an all-args constructor is explicitly declared.

Error #2: Private fields without getters/setters.
If you made all fields private but forgot to add getters and setters, Jackson won’t be able to populate them during deserialization (by default).

Error #3: Mismatched field names.
When a field name in JSON differs from the field/getter name in Java, Jackson won’t find a match. Use @JsonProperty.

Error #4: Wrong date format.
If the date format in JSON doesn’t match the format expected by Java, Jackson will throw a parsing error. Use @JsonFormat to configure it.

Error #5: Attempting to serialize fields annotated with @JsonIgnore.
Such fields won’t be included in JSON — that’s not a bug, it’s a feature.

Error #6: Serializing/deserializing collections without specifying the element type.
If you don’t use a TypeReference, Jackson won’t know what type of objects are inside the collection.

Error #7: Exception while reading/writing a file.
Don’t forget to handle IOException when working with files.

1
Task
JAVA 25 SELF, level 46, lesson 1
Locked
User Data Privacy 🕵️‍♀️
User Data Privacy 🕵️‍♀️
1
Task
JAVA 25 SELF, level 46, lesson 1
Locked
Event management in the university calendar 🗓️
Event management in the university calendar 🗓️
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION