


Solve the problem of default value when the Lombok Boolean field is missing in Jackson
Aug 04, 2025 pm 05:54 PMUnderstand Jackson deserialization and Java type default values
In Java, basic data types (such as boolean, int, double, etc.) have their default values. For example, the default value of boolean is false, and the default value of int is 0. However, their packaging types (such as Boolean, Integer, Double, etc.) are used as objects, and their default value is null.
When the Jackson library does JSON deserialization, it tries to map JSON data to fields of a Java object. If a field in JSON is missing, Jackson will handle it according to the type of Java field:
- For basic type fields : If the corresponding field is missing in JSON, Jackson will directly use the default value of the basic type. For example, if the negate field is of boolean type and no negate field is provided in JSON, then negate will be automatically initialized to false.
- For wrapping type fields : If the corresponding field is missing in JSON, Jackson will set it to null. This is because the wrapper type is an object and null is its valid "empty" state.
This is why when the negate field is defined as a Boolean, if the incoming JSON does not contain the negate field, it will be deserialized to null, which may cause a NullPointerException when trying to access negate.
Solution: Use the basic type boolean
The most straightforward and recommended way to solve this problem is to change the type of the field from the Boolean wrapper type to the boolean primitive type.
Consider the following original class definitions:
import lombok.AllArgsConstructor; import lombok.Data; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.List; @Data @AllArgsConstructor @ApiModel public class RelationEntityTypeFilter { @ApiModelProperty(position = 1, value = "Type of the relationship between root entity and other entity (eg 'Contains' or 'Manages').", example = "Contains") private String relationType; @ApiModelProperty(position = 2, value = "Array of entity types to filter the related entities (eg 'DEVICE', 'ASSET').") private List<entitytype> entityTypes; @ApiModelProperty(position = 3, value = "Negate relationship type between root entity and other entity.") private Boolean negate = false; // Problem: Boolean type}</entitytype>
Change the type of the negate field to boolean:
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; // It is recommended to add, if you need to deserialize the constructor without arguments import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.List; @Data @NoArgsConstructor // Add parameterless constructor to support Jackson deserialization @AllArgsConstructor @ApiModel public class RelationEntityTypeFilter { @ApiModelProperty(position = 1, value = "Type of the relationship between root entity and other entity (eg 'Contains' or 'Manages').", example = "Contains") private String relationType; @ApiModelProperty(position = 2, value = "Array of entity types to filter the related entities (eg 'DEVICE', 'ASSET').") private List<entitytype> entityTypes; @ApiModelProperty(position = 3, value = "Negate relationship type between root entity and other entity.") private boolean negate; // Solution: Change to boolean basic type// Note: = false here; initialization is no longer necessary, because boolean defaults to false }</entitytype>
When the negate field becomes boolean type, even if the incoming JSON does not contain the negate field, Jackson will set it to false when deserialized, thus avoiding NullPointerException.
Sample code verification
We can verify this behavior with a simple Jackson deserialization example.
First, define a simplified version of the class that only contains fields of type boolean:
import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; public class JacksonBooleanDefaultExample { @NoArgsConstructor @Getter @Setter @ToString public static class SimpleFilter { private boolean negate; // Use boolean basic type} public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); // Case 1: Negate field is missing in JSON String negateIsMissingJson = "{ }"; SimpleFilter filter1 = mapper.readValue(negateIsMissingJson, SimpleFilter.class); System.out.println("JSON missing field: " filter1); // Expected output: SimpleFilter(negate=false) // Case 2: Negate is explicitly specified in JSON to false String negativeIsFalseJson = """ { "negate" : false } """; SimpleFilter filter2 = mapper.readValue(negateIsFalseJson, SimpleFilter.class); System.out.println("JSON explicitly specifies false: " filter2); // Expected output: SimpleFilter(negate=false) // Case 3: Negate is explicitly specified in JSON to true String negateIsTrueJson = """ { "negate" : true } """; SimpleFilter filter3 = mapper.readValue(negateIsTrueJson, SimpleFilter.class); System.out.println("JSON explicitly specifies true: " filter3); // Expected output: SimpleFilter(negate=true) } }
Run the above code and the output will be:
JSON missing field: SimpleFilter(negate=false) JSON explicitly specifies false: SimpleFilter(negate=false) JSON explicitly specifies true: SimpleFilter(negate=true)
From the output, we can see that when the negate field is missing in JSON, the negate field of boolean type is correctly deserialized to false.
Best Practices and Precautions
- Priority use of basic types : For simple boolean flags, priority is given to boolean primitive types. It not only solves the default value issue when Jackson deserializing, but also has better memory efficiency and performance, as it does not require additional object overhead.
- When to use the wrapper type Boolean :
- When a field may need to represent three states: true, false, and null (e.g., "Yes", "No", "No/Unset"). But please note that this situation usually requires a clear business implication and should be used with caution in API design to avoid ambiguity.
- When it is necessary to store boolean values in a collection (such as List
, Map ), Java collections can only store objects. - When used as a generic parameter (e.g. Optional
).
- Lombok and default values : Lombok's @Data annotation will generate constructors, Getters/Setters, etc. If the field is a primitive type, Java's default initialization rules still apply. For boolean, it will be false. Even if = false is explicitly written when the field is declared, this is more of a hint of code readability for the boolean type, because Java will automatically initialize it to false.
- @JsonInclude(JsonInclude.Include.NON_NULL) : This Jackson annotation is usually used for serialization, indicating that if the field value is null during serialization, the field is not included. It does not affect the processing of null during deserialization. For the primitive type boolean, it is usually not set to null, so this annotation has little effect on it.
- @JsonProperty(defaultValue = "false") : Although Jackson provides the defaultValue property annotated by @JsonProperty, it is mainly used for document purposes or some specific data binding frameworks. Jackson's own deserializer usually does not directly use this property to set the default value of missing fields . Best practice is still to rely on the default behavior of the Java type itself or initialize it in the constructor/Setter.
Summarize
In Java applications, especially when using Jackson for JSON deserialization, it is crucial to the selection of Boolean fields. To avoid NullPointerException caused by missing fields in JSON and to ensure that the default behavior is as expected, it is strongly recommended to define a simple boolean flag as a boolean primitive type rather than a Boolean wrapper type. This not only simplifies code logic, but also improves program robustness and performance.
The above is the detailed content of Solve the problem of default value when the Lombok Boolean field is missing in Jackson. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Java supports asynchronous programming including the use of CompletableFuture, responsive streams (such as ProjectReactor), and virtual threads in Java19. 1.CompletableFuture improves code readability and maintenance through chain calls, and supports task orchestration and exception handling; 2. ProjectReactor provides Mono and Flux types to implement responsive programming, with backpressure mechanism and rich operators; 3. Virtual threads reduce concurrency costs, are suitable for I/O-intensive tasks, and are lighter and easier to expand than traditional platform threads. Each method has applicable scenarios, and appropriate tools should be selected according to your needs and mixed models should be avoided to maintain simplicity

In Java, enums are suitable for representing fixed constant sets. Best practices include: 1. Use enum to represent fixed state or options to improve type safety and readability; 2. Add properties and methods to enums to enhance flexibility, such as defining fields, constructors, helper methods, etc.; 3. Use EnumMap and EnumSet to improve performance and type safety because they are more efficient based on arrays; 4. Avoid abuse of enums, such as dynamic values, frequent changes or complex logic scenarios, which should be replaced by other methods. Correct use of enum can improve code quality and reduce errors, but you need to pay attention to its applicable boundaries.

JavaNIO is a new IOAPI introduced by Java 1.4. 1) is aimed at buffers and channels, 2) contains Buffer, Channel and Selector core components, 3) supports non-blocking mode, and 4) handles concurrent connections more efficiently than traditional IO. Its advantages are reflected in: 1) Non-blocking IO reduces thread overhead, 2) Buffer improves data transmission efficiency, 3) Selector realizes multiplexing, and 4) Memory mapping speeds up file reading and writing. Note when using: 1) The flip/clear operation of the Buffer is easy to be confused, 2) Incomplete data needs to be processed manually without blocking, 3) Selector registration must be canceled in time, 4) NIO is not suitable for all scenarios.

Java's class loading mechanism is implemented through ClassLoader, and its core workflow is divided into three stages: loading, linking and initialization. During the loading phase, ClassLoader dynamically reads the bytecode of the class and creates Class objects; links include verifying the correctness of the class, allocating memory to static variables, and parsing symbol references; initialization performs static code blocks and static variable assignments. Class loading adopts the parent delegation model, and prioritizes the parent class loader to find classes, and try Bootstrap, Extension, and ApplicationClassLoader in turn to ensure that the core class library is safe and avoids duplicate loading. Developers can customize ClassLoader, such as URLClassL

The key to Java exception handling is to distinguish between checked and unchecked exceptions and use try-catch, finally and logging reasonably. 1. Checked exceptions such as IOException need to be forced to handle, which is suitable for expected external problems; 2. Unchecked exceptions such as NullPointerException are usually caused by program logic errors and are runtime errors; 3. When catching exceptions, they should be specific and clear to avoid general capture of Exception; 4. It is recommended to use try-with-resources to automatically close resources to reduce manual cleaning of code; 5. In exception handling, detailed information should be recorded in combination with log frameworks to facilitate later

HashMap implements key-value pair storage through hash tables in Java, and its core lies in quickly positioning data locations. 1. First use the hashCode() method of the key to generate a hash value and convert it into an array index through bit operations; 2. Different objects may generate the same hash value, resulting in conflicts. At this time, the node is mounted in the form of a linked list. After JDK8, the linked list is too long (default length 8) and it will be converted to a red and black tree to improve efficiency; 3. When using a custom class as a key, the equals() and hashCode() methods must be rewritten; 4. HashMap dynamically expands capacity. When the number of elements exceeds the capacity and multiplies by the load factor (default 0.75), expand and rehash; 5. HashMap is not thread-safe, and Concu should be used in multithreaded

Polymorphism is one of the core features of Java object-oriented programming. Its core lies in "one interface, multiple implementations". It implements a unified interface to handle the behavior of different objects through inheritance, method rewriting and upward transformation. 1. Polymorphism allows the parent class to refer to subclass objects, and the corresponding methods are called according to the actual object during runtime; 2. The implementation needs to meet the three conditions of inheritance relationship, method rewriting and upward transformation; 3. It is often used to uniformly handle different subclass objects, collection storage and framework design; 4. When used, only the methods defined by the parent class can be called. New methods added to subclasses need to be transformed downward and accessed, and pay attention to type safety.

Java enumerations not only represent constants, but can also encapsulate behavior, carry data, and implement interfaces. 1. Enumeration is a class used to define fixed instances, such as week and state, which is safer than strings or integers; 2. It can carry data and methods, such as passing values ??through constructors and providing access methods; 3. It can use switch to handle different logics, with clear structure; 4. It can implement interfaces or abstract methods to make differentiated behaviors of different enumeration values; 5. Pay attention to avoid abuse, hard-code comparison, dependence on ordinal values, and reasonably naming and serialization.
