Mastering Jackson in Spring Boot: From Basics to Advanced Configuration

This article provides a comprehensive guide to using Jackson with Spring Boot, covering its core modules, Maven dependencies, ObjectMapper usage, JSON tree model, custom deserializers, XML handling, configuration options, and practical code examples for serialization and deserialization.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
Mastering Jackson in Spring Boot: From Basics to Advanced Configuration

What is Jackson

Jackson is a widely used Java library for JSON (and optionally XML) serialization and deserialization. It is the default JSON processor in Spring Boot.

Core Modules

jackson-core – low‑level streaming API (JsonParser, JsonGenerator).

jackson-annotations – standard annotations.

jackson-databind – data‑binding API (ObjectMapper, JsonNode) built on the two above.

Maven Dependencies

Spring Boot’s spring-boot-starter-web pulls in spring-boot-starter-json, which brings the Jackson modules automatically. If you need to add them manually, a typical set is:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-parameter-names</artifactId>
</dependency>

ObjectMapper – Core Class

ObjectMapper provides high‑level data‑binding: serialization, deserialization, and tree model access.

Serialize a Java object to JSON string.

Deserialize a JSON string to a Java object.

Parse JSON into a mutable tree ( JsonNode) for selective field access.

Typical Code Examples

Serialization and deserialization of a simple POJO:

public class WeChat {
    private String id;
    private String name;
    private String[] interest;
    // getters and setters
}

ObjectMapper mapper = new ObjectMapper();

// Java bean → JSON
String json = mapper.writeValueAsString(new WeChat("zhuan2quan", "程序新视界",
        new String[]{"Java","Spring Boot","JVM"}));
System.out.println(json);

// JSON → Java bean
WeChat bean = mapper.readValue(json, WeChat.class);
System.out.println(bean);

Convert JSON to a generic Map:

Map<String,Object> map = mapper.readValue(json,
        new TypeReference<Map<String,Object>>(){});
System.out.println(map);

Read/write JSON from/to a file:

mapper.writeValue(new File("weChat.json"), bean);
WeChat fromFile = mapper.readValue(new File("weChat.json"), WeChat.class);

Work with byte arrays:

byte[] bytes = mapper.writeValueAsBytes(bean);
WeChat fromBytes = mapper.readValue(bytes, WeChat.class);

JSON Tree Model

The tree model lets you navigate large JSON payloads without binding to a POJO. Example:

ObjectNode root = mapper.createObjectNode();
root.put("id", "zhuan2quan");
root.put("name", "程序新视界");
ArrayNode interest = root.putArray("interest");
interest.add("Java").add("Spring Boot").add("JVM");
String jsonTree = mapper.writeValueAsString(root);
System.out.println(jsonTree);

// Parse existing JSON
JsonNode node = mapper.readTree(jsonTree);
String name = node.path("name").asText(); // safe, returns MissingNode if absent
ArrayNode arr = (ArrayNode) node.get("interest");
for (JsonNode n : arr) {
    System.out.println(n.asText());
}
path()

returns a MissingNode for missing fields, avoiding null checks; get() returns null.

Streaming API (Brief Note)

Jackson also offers low‑level streaming via JsonParser and JsonGenerator, but most applications use the higher‑level data‑binding APIs shown above.

Global Configuration

Common ObjectMapper settings:

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT);

Since Jackson 2.2, JsonMapper provides a builder‑style API with the same capabilities.

Annotation‑Based Customization

@JsonProperty("json_name")

– map a JSON field to a different Java property. @JsonIgnore – exclude a field from both serialization and deserialization. @JsonIgnoreProperties({"prop1","prop2"}) – ignore listed properties globally. @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8") – format dates.

For Java 8 date‑time types, add the jackson-datatype-jsr310 module (included by Spring Boot).

Custom Deserializer Example

public class PointDeserializer extends JsonDeserializer<Point> {
    @Override
    public Point deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonNode node = p.getCodec().readTree(p);
        Iterator<JsonNode> it = node.get("coordinates").elements();
        double x = it.next().asDouble();
        double y = it.next().asDouble();
        return new Point(x, y);
    }
}

// Register the deserializer
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Point.class, new PointDeserializer());
mapper.registerModule(module);

XML Support

Jackson can process XML via the jackson-dataformat-xml module. Add the dependency:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

For Java 9+ add JAXB API to avoid NoClassDefFoundError:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
</dependency>

XML usage mirrors the JSON API; XmlMapper extends ObjectMapper:

XmlMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(bean);
System.out.println(xml);

Spring Boot Integration

Spring Boot auto‑configures an ObjectMapper bean. Override defaults via application.yml or a custom bean.

# application.yml
spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    deserialization:
      FAIL_ON_UNKNOWN_PROPERTIES: false
    serialization:
      INDENT_OUTPUT: true

Custom bean example:

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper jsonMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper mapper = builder.createXmlMapper(false).build();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return mapper;
    }
}

The injected ObjectMapper is thread‑safe and can be used throughout the application.

Reference

Jackson project on GitHub: https://github.com/FasterXML/jackson

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJSONSpring BootJacksonObjectMapper
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.