Skip to main content

Lesson 4 of 8

JSON Handling - Jackson

JSON is the universal data exchange format. Jackson is the most widely used Java JSON library - used by Spring Boot, Quarkus, and most REST frameworks. It converts Java objects to/from JSON (serialisation/deserialisation) with minimal boilerplate.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Jackson - ObjectMapper

Jackson - ObjectMapper
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.*;

// Jackson annotations for control over serialisation
public class BookDto {
    @JsonProperty("isbn")         // custom JSON field name
    private String isbn;

    @JsonProperty("title")
    private String title;

    @JsonIgnore                   // never include in JSON (passwords, sensitive data)
    private String internalCode;

    @JsonInclude(JsonInclude.Include.NON_NULL)  // skip null fields in output
    private String notes;

    @JsonFormat(pattern = "yyyy-MM-dd")  // custom date format
    private LocalDate addedDate;

    // Jackson needs a no-arg constructor OR @JsonCreator
    public BookDto() {}
    public BookDto(String isbn, String title) { this.isbn = isbn; this.title = title; }
    // Getters/setters...
}

public class JacksonDemo {
    public static void main(String[] args) throws Exception {
        // ObjectMapper - reuse as a singleton (thread-safe and expensive to create)
        ObjectMapper mapper = new ObjectMapper()
            .registerModule(new JavaTimeModule())    // java.time support (LocalDate, etc.)
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);  // tolerate extra fields

        // ── Object → JSON ────────────────────────────────────────
        BookDto book = new BookDto("001", "Effective Java");
        String json   = mapper.writeValueAsString(book);
        String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(book);
        System.out.println(json);    // {"isbn":"001","title":"Effective Java"}

        // ── JSON → Object ────────────────────────────────────────
        String incoming = """{"isbn":"002","title":"Clean Code","price":39.99}""";
        BookDto parsed = mapper.readValue(incoming, BookDto.class);

        // ── JSON → List of objects ────────────────────────────────
        String arrayJson = """[{"isbn":"001","title":"A"},{"isbn":"002","title":"B"}]""";
        List<BookDto> books = mapper.readValue(arrayJson,
            mapper.getTypeFactory().constructCollectionType(List.class, BookDto.class));

        // ── JSON → Map (dynamic/unknown structure) ─────────────────
        Map<String, Object> map = mapper.readValue(incoming, Map.class);
        System.out.println(map.get("title"));  // "Clean Code"

        // ── JsonNode - tree model (navigate without full class)─────
        JsonNode root     = mapper.readTree(incoming);
        String isbn       = root.get("isbn").asText();
        double price      = root.get("price").asDouble(0.0); // default 0 if missing
        boolean hasNotes  = root.has("notes");

        // ── File I/O ──────────────────────────────────────────────
        mapper.writeValue(new java.io.File("catalog.json"), books);
        List<BookDto> loaded = mapper.readValue(
            new java.io.File("catalog.json"),
            mapper.getTypeFactory().constructCollectionType(List.class, BookDto.class)
        );
    }
}

Quick Quiz

Tip

Tip

Practice JSON Handling Jackson in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for JSON Handling - Jackson

Practice Task

Note

Practice Task - (1) Write a working example of JSON Handling Jackson from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with JSON Handling Jackson is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done